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)
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")