"GetPlayerFromCharacter" returning nil

Hey there!

Im making a radio tool, which opens a gui from PlayerGui to place the audio ID.

However, the problem starts when getting the player, I used “GetPlayerFromCharacter” but it returns always nil (same with FindFirstAncestorWhichIsA)
image

And yes, the script is directly in the tool

image

So, do you know why this happens? here is the code im using, i used the print to check if i was actually referencing the player

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


script.Parent.Activated:Connect(function()
print(player)

	
end)

I hope you can help me, thanks!

That doesn’t matter, you can do it either way.

Also, if you’re expecting a player, I suggest you reference it inside the activated event, because the character is not the tool’s parent initially, activated is only called if you click while the tool is equipped (parented to the character at this point).

2 Likes

Since you are firing when activated, you could just change the player in there

script.Parent.Activated:Connect(function()
local player = game.Players:GetPlayerFromCharacter(script.Parent.Parent)
print(player)

	
end)

Or you could update the player when they equip the tool

Like this

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


script.Parent.Activated:Connect(function()
print(player)

	
end)

script.Parent.Equipped:Connect(function()
    player = script.Parent.Parent
end)

Edited to fix what I stated incorrectly

3 Likes

Why would that only run locally? It doesn’t really matter where you run it, it’s just a matter of where you reference it depending on the use case.

thank you! i forgot about that, now the script works!

The reason being that to actually get a player object as a parent, it would need to be running on the client. Server scripts can’t run anywhere where an ancestor could be a player object

They can though. I run my server scripts in the players backpack.

thank you too! you also helped to solve that problem xD

Oh, nvm. I didn’t realize that server scripts do run inside the backpack

1 Like