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

Help with function?

Asked by
FiredDusk 1466 Moderation Voter
8 years ago

****Error: 17:26:35.993 - Workspace.Slide.Part.Script:6: attempt to index local 'Player' (a nil value)

Not making me sit.

script.Parent.Touched:connect(function(hit)

        local Player = hit.Parent:FindFirstChild("Humanoid")


        Player.Sit = true

end)

3 answers

Log in to vote
2
Answered by 8 years ago

Because the Touched event fires whenever ANY physical object touched it (even ones that are not player models). And if that's true, we know most things in a game don't have humanoids in them. So when you're using findfirstchild for a Humanoid, and one doesn't exist, it will return a nil value. Then you're saying .Sit = true, which will cause an error since the script reads it as:

nil.Sit = true -- (since findfirstchild returned nil)

And then you'll get the infamous error message of: "Error, attempt to index global / local 'Player' (a nil value)"

We can easily fix this by adding some flow control to our function, based on the condition that the Humanoid actually exists before trying to change something that may not exist, like this:

script.Parent.Touched:connect(function(hit)

        local Player = hit.Parent:FindFirstChild("Humanoid")

    -- The code under this if statement will run if it's "Player" condition is true (which it will be, if it exists. If it doesn't, the script will simply ignore it without breaking.)

    if Player then
        Player.Sit = true
    end

end)

Hope it helped.

Ad
Log in to vote
1
Answered by
NotSoNorm 777 Moderation Voter
8 years ago

Not sure if this will solve it but hey,

script.Parent.Touched:connect(function(hit)
    local hitter = hit.Parent:FindFirstChild("Humanoid")
    if hitter then --check to see if "humanoid" is a valid member of what hit it
        hitter.Humanoid.Sit = true --changes the humanoid value, not the player
    end
end)

0
No need to search for a humanoid inside a humanoid, you already referenced it. ScriptGuider 5640 — 8y
Log in to vote
1
Answered by 8 years ago
script.Parent.Touched:connect(function(hit)

        local Player = game.Players:GetPlayerFromCharacter(hit.Parent) -- gets player (possibly redundant but hey)
        local humanoid = Player.Character.Humanoid -- gets player's humanoid

        if humanoid then
        humanoid.Sit = true
end
end)

I tested it in studio and it worked. Enjoy.

Answer this question