When is it appropriate to use WaitForChild?

I’m having a hard time knowing when I should be using WaitForChild, and when I should be using FindFirstChild…
For example, if I’m getting an object from ReplicatedStorage should I always be using WaitForChild?

Thanks.

7 Likes

only use WaitForChild when something is being created such as a players character or a leaderstats Folder.

2 Likes

I’m too paranoid about messing up an entire script, so it’s nice to use WaitForChild:(). It ensures that you get the object you’re referring to, no matter what. I’m no expert, but I would use WaitForChild:() for basically everything that needs to load in. However, if the script works fine without WaitForChild:(), that’s completely fine and don’t be afraid to not use it.

2 Likes

You can see a detailed write up of this here:

The short answer is: you use WaitForChild when the Instance you need a reference to has to either replicate from another computer (server to client, or client to server), or it’s being created at runtime by another script on the same computer (e.g. a server Script is creating new Instances in Workspace, and other server Scripts are waiting for them to be generated).

The biggest gotcha with WaitForChild is that if you don’t supply a duration, and you wait for something that isn’t coming (due to error, wrong name, etc) it can block forever and prevent other parts of your script from executing. For this reason, I often do client-side WaitForChild things in a coroutine, and I put generous (but not infinite) time limits on things I expect to replicate quickly, like 60 seconds, so that the failures are not silent. When you do this, uses of the reference following the WaitForChild call have to account for the reference possibly being nil.

20 Likes

This is also a common pitfall of Roblox developers. Even in accurate play solo, your server and client are still the same machine and Studio does not simulate any network latency between them. So something can work 100% of the time in local testing with FindFirstChild, but fail in a real client-server scenario (because it’s actually a race condition).

6 Likes