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

Problems with a simple script using functions?

Asked by 6 years ago

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

Log in to vote
1
Answered by 6 years ago
Edited 6 years ago

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.
Ad
Log in to vote
-2
Answered by 6 years ago

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
Explain your answers. OldPalHappy 1477 — 6y

Answer this question