I made this extremely simple script, but for some reason it decides not to work.
Here is the script:
function onTouched(part, plr) local h = part.Parent:findFirstChild("Humanoid") if h~=nil then h.Health = 0 print(plr.Name .. " has died!") --this is line 5 end end script.Parent.Touched:connect(onTouched)
Here is the error I get:
Workspace.Kill brick.Code:5: attempt to index local 'plr' (a nil value)
This has never been a problem when I use multiple arguments in a function. Can someone help?
.Touched
doesn't provide the player as an argument to the function, it only provides the BasePart
that touched the Instance. For this reason, plr
is nil.
You can get the player via GetPlayerFromCharacter
. But you don't really need the player for what you're doing now. You can just use the character, which would be hit.Parent
local function onTouched(part) local h = part.Parent:findFirstChild("Humanoid") if h~=nil then h.Health = 0 print(part.Parent.Name) -- part.Parent is the character, and the character name should be the same as the player name end end script.Parent.Touched:connect(onTouched)
local
to the function to make it a local function, something I'd recommend you get into the habit of doing.Try this code instead
function onTouched(part) if part.Parent:FindFirstChild("Humanoid") ~= nil then local plr = game.Players:FindFirstChild(part.Parent.Name) if plr then local h = part.Parent:findFirstChild("Humanoid") if h~=nil then h.Health = 0 print(plr.Name .. " has died!") --this is line 5 end end end end script.Parent.Touched:connect(onTouched)