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

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

Asked by 6 years ago
Edited 6 years ago
local Handle = script.Parent:WaitForChild("Handle")

Handle.Touched:Connect(function(plr)
    local Player = game.Players:GetPlayerFromCharacter(plr.Parent)
    if Player.Character.Humanoid then
        if Player.Character ~= game.Players.LocalPlayer then
            Player.Character.Humanoid.Health = 0
            for _,i in pairs(Player.Character:GetChildren()) do
                if i.BrickColor then
                    i.BrickColor = BrickColor.Random()
                end
            end 
        end
    end
end)

Getting the error "Players.NAME.Backpack.Taser.LocalScript:5: attempt to index local 'Player' (a nil value)" error. I don't get why

1 answer

Log in to vote
0
Answered by 6 years ago

The reason for this is quite simple. When GetPlayerFromCharacter was called on line 4, you continued to use it despite it returning nil, so the script saw it like nil.Character. In order to fix this, simply check if the player exists.

local Handle = script.Parent.Handle

Handle.Touched:Connect(function(part)
    local Player = game.Players:GetPlayerFromCharacter(part.Parent)

    if Player then -- if Player exists 
        if Player.Character ~= script.Parent.Parent then
            -- Assuming this is under a Tool, script.Parent.Parent is the character if the script is directly under tool 
            Player.Character.Humanoid.Health = 0

            for _,i in pairs(Player.Character:GetChildren()) do
                if i:IsA("BasePart") then -- If it is a part, it has a BrickColor property. 
                    i.BrickColor = BrickColor.Random()
                end
            end 
        end
    end
end)

0
tool.Equipped instead 129Steve129 7 — 6y
0
no User#19524 175 — 6y
Ad

Answer this question