Trying to make the check that will prevent the script from breaking when a bullet hits the brick.
script.Parent.Touched:connect(function(hit) if hit.Parent and hit.Parent:FindFirstChild("Humanoid") then hit.Parent.Humanoid.Health = 0 end end)
script.Parent.Touched:connect(function(hit) if hit.Parent then if hit.Parent:FindFirstChild("Humanoid") then hit.Parent.Humanoid.Health = 0 end end end)
I'm more inclined to use the first option, because it's cleaner, but I was worried that in the case hit.Parent
doesn't exist, the part where it looks for a Humanoid would error because it assumes hit.Parent
does exist. Therefore I'm not sure. Which one should I use? Please explain why I should use that particular option in your answers. Thanks.
Neither is better in terms of the check. I would opt for the first because it's shorter and clearer -- fewer levels of indentation is almost always better (and the condition isn't long or unclear to accomplish it)
You're right to be suspicious about the first one, since after all, it looks like it checks both.
There's a bit of magic to how and
works. Unlike most operations, it only evaluates what it needs to, starting at the left.
That means if the thing on the left is already false
, it won't even bother checking the thing on the right (so the thing on the right is never executed to cause an error).
This is called short circuiting and it applies to or
too (except that it stops if there's a truthy value instead). It's a form of lazy evaluation, and the only real such form in Lua.
Use the first one as it is cleaner.
It will work no matter what, if not then try this:
Putting else
will basically say if the object that has hit
and does not have the Humanoid
it will just end the script.
script.Parent.Touched:connect(function(hit) if hit.Parent and hit.Parent:FindFirstChild("Humanoid") then hit.Parent.Humanoid.Health = 0 else end end)
script.Parent.Touched:connect(function(hit) if(hit.Parent)and(game.Players:playerFromCharacter(hit.Parent))then hit.Parent.Humanoid.Health=0 end end)