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 comment
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.