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