Is their a way to check if something exists without getting errors

So I basically I have a gun. When the gun hits a part its checks if it has a humanoid in it by doing:

if model:FindFirstChild("Humanoid") then

It works but whenever it hits a part with no humanoid I get this error

attempt to index nil with 'FindFirstChild’

Whats the best way to deal with this? Is there an alternate way, or should I just ignore error.

2 Likes

It’s because model is nil. It’s saying you’re looking inside of nil for a function called FindFirstChild

2 Likes

I know why its producing the error, I just don’t know how to deal with it.

2 Likes

Share the entire script (or at least a larger snippet relevant to the issue).

Use if model then

Edit: You can use if model and model:FindFirstChild('Humanoid') then. With the and operator, if the first condition is falsy (nil or false), it won’t evaluate the second expression, therefore causing no errors.

5 Likes

Maybe you could use an else statement to break out of the if statement if there is not humanoid?

ex:

if model:FindFirstChild("Humanoid") then
   -- Do your stuff
else
   print("No humanoid found!")
end
if model:FindFirstChild("Humanoid") then
			model.Humanoid.Health -= 50
			end
		end 

model does not exist dude

:findfirstchild will not return an error like that, you are indexing nil (the model) with the findfirstchild

I had it as a variable I forgot to grab it, that on me.

if model then
	if model.Humanoid then
		--some code
	else
		print("no humanoid in model")
	end
else
	print("no model found")
end

if model then
if model.somethingelse then
if model.somethingelse.thirdthing then
etc…

I suggest not doing this and instead use the and operator since this can cause loads of unneeded indentation which is hard to read.

1 Like

I actually use all layers of nested if statements like this. If the Character exists, but the Humanoid does not, for example, I build the Humanoid. If the Character doesn’t exist, how did I get here?

AND statements are good when you are confident you will never want to know why the code broke.