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

projectiles create error spam?

Asked by
jlpt 0
6 years ago

i have a weapon that summons projectiles and when they hit a target

vvv

function onTouched(part)    
local enemy = part.Parent

if enemy.Humanoid ~= nil then

part.Parent.Humanoid.Health = part.Parent.Humanoid.Health - 5
script.Parent:Remove()

end
end

script.Parent.Touched:connect(onTouched)

but everytime it hits something it spams errors is there a way to make it so that it doens't create errors?

0
Be sure to post what the errors are so we can better help you. Errors actually have a lot of useful information in them that we can use. User#18718 0 — 6y

1 answer

Log in to vote
0
Answered by 6 years ago
Edited 6 years ago

The correct way to check for a Humanoid instance is not to look up the Humanoid so-called attribute. I bet the error said something like failed to index field Humanoid of instance Part. This is because if Humanoid doesn't exist, it assumes you are calling an attribute of the object itself, not a child.

We can clean this up by creating a variable for our humanoid (that way we don't need to reference it with so much text) and using the method FirstFirstChildOfClass. Now we could use FindFirstChild and assume the name of the Humanoid is Humanoid but I don't want to assume that (some enemies from free models for example can have a renamed Humanoid).

We will check for the Humanoid (class) with the following.

local humanoid = enemy:FindFirstChildOfClass("Humanoid")
if humanoid then
...

If FindFirstChildOfClass cannot find Humanoid, it will return the nil value. This interprets as something false in an if statement.

Your script in the end will look like the following.

function onTouched(part)    
local enemy = part.Parent
local humanoid = enemy:FindFirstChildOfClass("Humanoid") or enemy.Parent:FindFirstChildOfClass("Humanoid") 
if humanoid then

humanoid.Health = part.Parent.Humanoid.Health - 5
script.Parent:Remove() 

end
end

script.Parent.Touched:connect(onTouched)

EDIT: Adjusted a line to read enemy:FindFirstChildOfClass in final script and used hiimgoodpack's suggestion of checking the parent as well.

1
You should also check the humanoid by doing part.Parent.Parent for accessories. hiimgoodpack 2009 — 6y
0
Good catch, I added it to my answer. Luckily `or` can make it a one line change. User#18718 0 — 6y
Ad

Answer this question