I have made this script that is designed to hurt non-player humanoids, however it does not work. What am I doing wrong here?
function enemy(hit) local h = hit.Parent:findFirstChild("Humanoid") local name = h.Parent local player = game.Players.FindFirstChild(name) if h ~= nil then if name ~= player then h.Health = h.Health - 100 end end end script.Parent.Touched:connect(enemy)
When I use the script I get these errors, the first one I think is supposed to happen but I really don't know what to make of the second.
21:17:00.905 - Workspace.Player.Tool.arrow.Script:4: attempt to index local 'h' (a nil value) 21:17:00.906 - Stack Begin 21:17:00.907 - Script 'Workspace.Player.Tool.arrow.Script', Line 4 21:17:00.908 - Stack End 21:17:00.985 - Argument 1 missing or nil 21:17:00.986 - Script 'Workspace.Player.Tool.arrow.Script', Line 5 21:17:00.987 - Stack End
You defined "name" as h.Parent which is an object(a model). You should do:
name = h.Parent.Name
.Name get's the name of the object.
But we also have to deal with some other problems, if hit doesn't have a humanoid then it would return nil and break the script so by adding a simple if statement this could be fixed.
if hit ~= nil and hit.Parent and hit.Parent:FindFirstChild("Humanoid") then
Then we have to make sure that it's not a player by using GetPlayerFromCharacter()
if hit ~= nil and hit.Parent and hit.Parent:FindFirstChild("Humanoid") and game.Players:GetPlayerFromCharacter(hit.Parent) == nil then
Final code:
function enemy(hit) if hit ~= nil and hit.Parent and hit.Parent:FindFirstChild("Humanoid") and game.Players:GetPlayerFromCharacter(hit.Parent) == nil then hit.Parent:FindFirstChild("Humanoid").Health = hit.Parent:FindFirstChild("Humanoid").Health - 100 end script.Parent.Touched:connect(enemy)
First, you did not include a capital F in the first findFirstChild
function. Also, you need to change the declaration of name
to hit.Parent.Name
. There might be a few other problems, but that's all I can see.