I have made this script that is designed to hurt non-player humanoids, however it does not work. What am I doing wrong here?
01 | function enemy(hit) |
02 | local h = hit.Parent:findFirstChild( "Humanoid" ) |
03 | local name = h.Parent |
04 | local player = game.Players.FindFirstChild(name) |
05 | if h ~ = nil then |
06 | if name ~ = player then |
07 | h.Health = h.Health - 100 |
08 | end |
09 | end |
10 | end |
11 |
12 | 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.
1 | 21 : 17 : 00.905 - Workspace.Player.Tool.arrow.Script: 4 : attempt to index local 'h' (a nil value) |
2 | 21 : 17 : 00.906 - Stack Begin |
3 | 21 : 17 : 00.907 - Script 'Workspace.Player.Tool.arrow.Script' , Line 4 |
4 | 21 : 17 : 00.908 - Stack End |
5 | 21 : 17 : 00.985 - Argument 1 missing or nil |
6 | 21 : 17 : 00.986 - Script 'Workspace.Player.Tool.arrow.Script' , Line 5 |
7 | 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.
1 | 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()
1 | if hit ~ = nil and hit.Parent and hit.Parent:FindFirstChild( "Humanoid" ) and game.Players:GetPlayerFromCharacter(hit.Parent) = = nil then |
Final code:
1 | function enemy(hit) |
2 | if hit ~ = nil and hit.Parent and hit.Parent:FindFirstChild( "Humanoid" ) and game.Players:GetPlayerFromCharacter(hit.Parent) = = nil then |
3 | hit.Parent:FindFirstChild( "Humanoid" ).Health = hit.Parent:FindFirstChild( "Humanoid" ).Health - 100 |
4 | end |
5 |
6 | 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.