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

Attempt to Index?

Asked by 9 years ago

I'm creating a Death Brick script and i tried many ways but i always get an index error.

Script:

function onTouch(hit)
    Player = game.Players:getPlayerFromCharacter(hit.Parent)
    h = Player:findFirstChild("Humanoid")
if h then
    h.Health = 0
    --print(("The noob %s died"):format(h.Parent.Name)) //Only enable if you're willing to have a spammed console.
    end
end
script.Parent.Touched:connect(onTouch)

Error: attempt to index global 'player' (a nil value)

1 answer

Log in to vote
3
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
9 years ago

You're attempting to index (use :) on Player, but Player is nil so you can't do that.


If hit.Parent isn't the Character of any Player object, then :getPlayerFromCharacter returns nil. You want to make sure that Player is actually a player:

function onTouch(hit)
    Player = game.Players:getPlayerFromCharacter(hit.Parent)
    if Player then
        h = Player:findFirstChild("Humanoid")
        if h then
            h.Health = 0
            --print(("The noob %s died"):format(h.Parent.Name)) //Only enable if you're willing to have a spammed console.
        end
    end
end
script.Parent.Touched:connect(onTouch)

You figured it out but I just now see a mistake:

The Player won't have a Humanoid in it: it's hit.Parent that will have the humanoid!

h = hit.Parent:FindFirstChild("Humanoid")

I would remark that using the string format function is probably not what you want to do... You could use simple concatenation, or the fact that print takes as many arguments as you want:

-- One of these would be better:
print("The noob", h.Parent.Name, "died")
-- or
print("The noob " .. h.Parent.Name .. " died")
0
The print was put on there for fun :P. KnownDev 0 — 9y
0
It no longer kills the player. Why is that? KnownDev 0 — 9y
1
NEVERMIND, I figured that out. KnownDev 0 — 9y
Ad

Answer this question