Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Why does "attempt to index a nil value" occur on plr variable?

Item = script.Parent:FindFirstChildOfClass("Tool")

  

script.Parent.Touched:Connect(function(hit)

local plr = game.Players:GetPlayerFromCharacter(hit.Parent) or game.Players:GetPlayerFromCharacter(hit.Parent):Wait()-- Here the error pops up(Script:4: attempt to index a nil value)

if plr.Backpack:FindFirstChild(Item.Name)== nil and hit.Parent:FindFirstChild(Item.Name) == nil then

local Clone = Item:Clone()

plr.Backpack:ClearAllChildren()

hit.Parent:FindFirstChildOfClass("Tool"):Remove()

Clone.Parent = hit.Parent

end

end)

1 answer

✓ Accepted answer

It seems like you're unclear of what game.Players:GetPlayerFromCharacter(char) does. char would be the model of the player's character, and the function returns the player of that character.

To clear things up, how part.Touched:Connect(function(hit) end) works is that hit is the part that touches part. This part can be the player's body part. This is why you use hit.Parent. hit.Parent is the player's character model. This is how Players:GetPlayerFromCharacter(char) works, if char is a player's model, it returns that player. However, if char isn't a player's character, it will return nil.

Now on to your issue: When you use game.Players:GetPlayerFromCharacter(hit.Parent), and hit.Parent is not a player's character, it will return nil, hence using :Wait() on it is essentially doing nil:Wait(), which is why it says "attempt to index a nil value".

Solution:

local plr = game.Players:GetPlayerFromCharacter(hit.Parent)
if plr then
	-- do stuff if plr exists. if hit.Parent isn't a player's character,
	-- the part that touched isn't a player so there's no need to run the code.
end

Hope this helps.

This discussion is preserved as it was. New answers, comments, and votes are closed.