iamnoamesa's script has very good explanations (so be sure to read it!). However, there is a flaw: in games where projectiles might remove themselves when they hit something, you must always make sure that "hit.Parent" is not nil; otherwise, if your ball happens to hit such a projectile, the script will try to index a nil value.
One extra point of note: if hum ~= nil then is practically the same as if hum then (unless hum might be false). You can put anything inside an if then and it'll be considered true so long as the value is neither nil nor false. There is nothing wrong with if hum ~= nil then, however, it's just longer.
So, a possible fixed script (assuming you define Ball somewhere, like iamnoamesa says) would be:
Ball.Touched:connect(function(hit)
if not hit.Parent then return end
local hum = hit.Parent:FindFirstChild("Humanoid")
if not hum then return end
hum:TakeDamage(20)
Ball:Destroy()
end)
if not hit.Parent then return end is the only line missing from iamnoamesa's script. Other changes are unimportant.
1 comment
If you wish to respect forcefields, use "hum:TakeDamage(20)" instead of "hum.Health = hum.Health - 20"