Why is GetPlayerFromCharacter returning as nil?

I’m trying to create a tool for the first time and it seems like I’ve run into an error. I was setting up the basic function of the tool and I was just about to add a currency function but I’m having issues getting the player, I can’t even get the players name. I’ve tried for about 2 hours to solve the issue but no luck. I don’t even understand what’s happening. When I do print("Player") it returns as nil.

To my understanding game.Players:GetPlayerFromCharacter(script.Parent.Parent) should work, right?
image

local player = game.Players:GetPlayerFromCharacter(script.Parent.Parent)
local Active = false
script.Parent.Activated:Connect(function()
	if Active == false then
		Active = true 
		animation = script.Parent.Parent.Humanoid:LoadAnimation(script.Parent.Animation)
		animation:Play()
		animation.Stopped:Wait()
		print(player.Name)
		wait(1)
		Active = false
	end	
end)


script.Parent.Unequipped:Connect(function()
	animation:Stop()
end)
1 Like

Because tool’s parent is not the character when it’s not equipped.
Tool’s parent is Player’s backpack when unequipped.
You can get the player who owns the tool like this:

local player = game:GetService("Players"):GetPlayerFromCharacter(script.Parent.Parent) or script.Parent.Parent.Parent

Of course this will only work if you’re sure that player can’t drop the tool and have it with them for all time.

2 Likes

The problem is most probably that the script is running while it’s not in your character. When the tool isn’t equipped, the parent will be the player’s backpack, and not their character. You could connect tool.Equipped to then activate the GetPlayerFromCharacter.

1 Like

The issue here was stated before by @BenMactavsin and @SanctuaryIX already. However, your solution here would be to move your entire player variable inside the .Activated connection. The only way .Activated can fire is if the player activates the tool, which would not be possible while in their backpack.

Ex:

local Active = false
script.Parent.Activated:Connect(function()
    local player = game.Players:GetPlayerFromCharacter(script.Parent.Parent)
	if Active == false then
		Active = true 
		animation = script.Parent.Parent.Humanoid:LoadAnimation(script.Parent.Animation)
		animation:Play()
		animation.Stopped:Wait()
		print(player.Name)
		wait(1)
		Active = false
	end	
end)


script.Parent.Unequipped:Connect(function()
	animation:Stop()
end)
2 Likes