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

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

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

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)

2 comments

0

tool.Equipped instead

0

no

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