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.
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)
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()