Question : Does scripts error are bad / cause lag?

Hello, if you don’t want to read all this you can go in the last sentence where i just ask the main question without context.

Context: In my game, I have a 230-line loop (runservice.PreRender) that handles all game mechanics (in a local script). The loop is only useful when the player character is alive. If I never want to have an error, then I have to add lots of if plr.Character and plr.Character:FindFirstChild(‘HRP’) or plr.Character:FindFirstChild(‘Hum’) .

I could do a single check at the start of the loop, but the frames are constantly stopped with lots of task.wait() for optimization so it could cause an error when a player dead (the error doesn’t break the script, but it’s an error).

So my question is this: Should I do a single check at the start of the script and if I don’t find the character or humanoid Root Part then I don’t run the loop ? (which means the script can cause an error every time the player dies) Or should I add lots of if player.character and plr.Character:FindFirstChild(‘’) to make sure I never get an error?

Shortcut: can script errors cause lag? Is it better to have lots of if char:FindFistChild(‘’) in a loop, or just one, with the risk of a few errors?

Thank you very much for help

1 Like

When a script errors it has to do a process called “unwinding” which is slow. You should not allow a script to have errors, even if they don’t cause any problems. :WaitForChild() is a version of FindFirstChild() that yields until the child with the requested name appears, using an event to do so instead of yielding. This is probably what you should use in your case.

1 Like

I get it , thank you for your help ! =)

Another litte question : I noticed than if i do :

character:WaitForChild('HRP',0) 
if character then

does the same than

character:FindFirstChild('HRP') 
if character then

Should i use FindFirstChild for the case ? I guess yes as it’s here for that, but i still ask because in documentation it’s mentionned that FindFirstChidl(‘’) isn’t the best for performance while nothing is mentionned for WaitForChild

Thank you again

I can make an educated guess as to how WaitForChild works:
It tries to find the child as if it already exists, this would have to do the exact same thing as FindFirstChild, since its supposed to behave the same.
If the child is not found, it waits on the ChildAdded event, which is disconnected if the timeout expires. When a new child is added, it checks if this is the child being waited for and returns it if so, otherwise it keeps waiting.

If that is true, which I think is reasonable, then there’s no difference, except that FindFirstChild makes it clear that you do not want to wait if it’s not there, which could matter for readability.

1 Like

Thank you so much ! I didn’t know that

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.