ItIs_Super
(Conner)
September 21, 2021, 10:32pm
#1
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
7z99
(cody)
September 21, 2021, 10:43pm
#2
It’s because model is nil. It’s saying you’re looking inside of nil for a function called FindFirstChild
2 Likes
ItIs_Super
(Conner)
September 21, 2021, 10:45pm
#3
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).
7z99
(cody)
September 21, 2021, 10:47pm
#5
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
CC_1204
(Zech)
September 21, 2021, 10:48pm
#6
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
ItIs_Super
(Conner)
September 21, 2021, 10:49pm
#7
if model:FindFirstChild("Humanoid") then
model.Humanoid.Health -= 50
end
end
Juicy_Fruit
(Juicy_Fruit)
September 21, 2021, 10:51pm
#8
model does not exist dude
:findfirstchild will not return an error like that, you are indexing nil (the model) with the findfirstchild
ItIs_Super
(Conner)
September 21, 2021, 10:52pm
#9
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
GolgiToad
(GolgiToad)
September 21, 2021, 10:52pm
#11
if model then
if model.somethingelse then
if model.somethingelse.thirdthing then
etc…
7z99
(cody)
September 21, 2021, 10:55pm
#12
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
GolgiToad
(GolgiToad)
September 21, 2021, 11:05pm
#13
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.