Do I need to use WaitForChild() in localscripts for GUIs in StarterGui?

Hello,

I don’t fully understand WaitForChild(), even though I’ve read the Dev page on it. And I need help understanding something that has been puzzling me: Do I need to use WaitForChild() in localscripts for GUIs in StarterGui?

1 Like

It’s good practice, but your code will usually work regardless of if you use WaitForChild in that scenario.

WaitForChild() is used when you need to wait for an object to exist in a specific location. For example, let’s say you make a new part in game.Workspace with Instance.new() and name it “Thing”. In order to refer to it, developers will often use game.Workspace:WaitForChild("Thing") to ensure the item exists. If they didn’t use WaitForChild and simply referred to it as game.Workspace.Thing, they risk their code erroring because the part might not exist.

In conclusion, if you are adding or cloning a part through a script, WaitForChild waits for the item to exist in a folder to make sure the code doesn’t error.

1 Like

WaitForChild() yields the script until the spefic object has loaded in, so if your script loads in before the object make sure to use it.

1 Like

I haven’t had a problem with not using it in this scenario. Generally, WaitForChild is used in cases where you’re not sure that the instance won’t immediately be there. For example, if you encounter an error such as 'x' is not a valid member of 'y', you should consider using WaitForChild. However, if you’re 100% sure that it will not error, using x:WaitForChild(y) is actually slower than x.y. Also, if you find yourself repeating WaitForChild calls (eg. a:WaitForChild(b):WaitForChild(c):WaitForChild(d)), I highly recommend this module: WaitForPath: A Solution To Endless WaitForChild Calls.

2 Likes