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

Problems with a simple script using functions?

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?

2 answers

✓ Accepted answer

Different events provide different arguments.


.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)
I also added 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)

1 comment

1

Explain your answers.

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