Why is the player a nil value?

So I’ve been trying to make a tool where when the player clicks it, it will print the player’s name. However, each time I test it out and click it, it prints Plr is a nil value.

Current Script:

local tool = script.Parent
tool.Activated:Connect(function(plr)
print(plr.Name)
end)

I tried looking on youtube for answers, I asked for help from my friends, which they did not respond to, and it has been doing this for all of my attempts to a click-able objects. Any ideas on why this is happening?

I don’t believe Player is passed in as an argument for the event - but you can get the player by referencing them through the game objects.

Whenever a Tool is activated, it’ll be inside the Character (this is what happens when the Tool is equipped). From there, game.Players has a method called GetPlayerFromCharacter which’ll return the Player given their Character, so you can do this:

local tool = script.Parent
tool.Activated:Connect(function()
local character = tool.Parent
local plr = game.Players:GetPlayerFromCharacter(character)
print(plr.Name)
end)

And from that point on (after the local plr line), you’ll be able to reference their player from inside the plr variable, so whatever else you were looking to do with it can be done there.

8 Likes

What if I do something like a button on a model that certain people could activate the effects? Lets say there is a userid checker in the button and if it is valid then whatever is in the function runs. Any tips on how to go about it?

You don’t even have to do this since by default the tools spawn on Backpack so the variables will be referenced from there. You can just directly get the player.

1 Like

I had a feeling there was something like that but wasn’t sure where the code first runs from so didn’t want to get it wrong. Thanks for the correction!

1 Like

Bit out of the topic but here you go


 local ClickDetector = script.Parent.ClickDetector
 local SpecifiedUserId = {123, 321, 231}

function SearchTable(tbl, value)  
    local bool
    bool = false
    for i,v in pairs(tab) do
        if v == value then
            bool = true
            return bool
        end
    end
end



 ClickDetector.MouseClick:Connect(function(Player)

  if  SearchTable(SpecifiedUserId, Player.UserId) then
   RunFunction()
  end

 end)
2 Likes