Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

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

Asked by 5 years ago

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.

0
Does this error occur directly after running the game? or does it occur when you touch the brick? MezornoIV 25 — 5y
0
when you touch the brick BiGGuNAaroN -6 — 5y

2 answers

Log in to vote
1
Answered by 5 years ago
Edited 5 years ago

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)
0
thank you so much this worked and explained it in a way i could understand. BiGGuNAaroN -6 — 5y
Ad
Log in to vote
0
Answered by 5 years ago

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

Answer this question