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

attempt to index local 'Player' (a nil value)?

Hello guys i'm currently making a game the requires me to have a Part that a player touches and it will remove them from there current job. The only problem is i keep getting this error "Workspace.EndWork.Part.End Work:4: attempt to index local 'Player' (a nil value)"

script.Parent.Touched:connect(function(hit)
    local Character = hit.Parent:FindFirstChild("Humanoid")
    local Player = game.Players:GetPlayerFromCharacter(Character)
    if Player.Core.InWork.Value == true then
	    Player.Core.InWork.Value = false
	    Player.TeamColor = game.Teams['Civilian'].TeamColor
	    print(Player.Name .. " Finished work!")
	    else
    end
end)

Any help would be greatly welcomed. thank you in advanced guys.

2 comments

0

Does this error occur directly after running the game? or does it occur when you touch the brick?

0

when you touch the brick

2 answers

✓ Accepted answer

Not everything that touches a part is someone's character, and even if it is, the primary reason your script cannot work as-is is because you're using the GetPlayerFromCharacter() method, but passing a humanoid as its argument. Here's what you need to do:

script.Parent.Touched:Connect(function(hit)
    -- It looks like you're not actually doing anything with the character, but for the sake of consistency, I'll keep the variable
    local Character = hit.Parent -- NOT hit.Parent:FindFirstChild('Humanoid') because the character is not a humanoid
    local Player = game.Players:GetPlayerFromCharacter(Character)
    if not Player then return end -- You have to check to make sure the player actually exists, as it is possible that the object touching your part does not belong to a character
    -- Rest of your code goes here
end)

1 comment

0

thank you so much this worked and explained it in a way i could understand.

The nil value error will occur when Player is not defined properly. This means that most-likely you don't actually get a player from the hit. I would suggest testing first using an if-statement to test if hit.Parent:FindFirstChild("Humanoid") exists, if it doesn't then do nothing. Remember Touched() looks for a part, not specifically a player. This means if another part in the game (baseplate, floor, etc) touches the object, it will fire the Touched() event.

Source: Wiki Entry: BasePart.Touched()

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