Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Is WaitForChild() better than Instance:Wait()?

I'm wondering if I should use Instance:Wait() to wait for something to get loaded in.

3 answers

✓ Accepted answer

WaitForChild() and Wait() are not the same thing. I'll explain.

RBXScriptSignal:Wait()

Wait() is a function used on events (NOT instances) that makes the script yield until the event fires. Furthermore, Instance:Wait() is not a valid function.

An example of using Wait():

script.Parent.Touched:Wait()
print("part has been touched")

Wait() only yields once and does not listen more than once, unlike Connect(), which listens infinitely. A debounce is not necessary for this reason. If the event never fires, Wait() can infinitely yield, which is a problem because it makes a script "hang", or never get past the line that Wait() was called on. Because of this, the rest of the script will never run.

Instance:WaitForChild()

WaitForChild() will yield until the Instance it is given is not nil. This is usually the best way to find a child of an Instance because instead of searching once like FindFirstChild(), WaitForChild() will wait for the child to exist. The function has 2 parameters:

  • The name of the child, given as a string (required)

  • How many seconds to wait until the function should stop yielding (optional). This is good for slow connections to the server.

Here is a rather simple example of using WaitForChild():

local event = game:GetService("ReplicatedStorage"):WaitForChild("RemoteEvent")

You may see that many people use WaitForChild() on RemoteEvents in particular. This is because ReplicatedStorage's descendants tend to be some of the last Instances to load in, and therefore FindFirstChild() can return nil if used on a slow connection.

However, that doesn't mean that WaitForChild() can't return nil; it can, but only if you're using the second parameter. If no second parameter is given and the child cannot be found (i.e. the child is nil), WaitForChild() throws an infinite yield warning and may stop yielding for the child. However, unlike errors, it won't stop the script from running.

Yes as PurpleProgram says. Please PLEASE use this. Its way more responsive and works way better than Instance:Wait()

This discussion is preserved as it was. New answers, comments, and votes are closed.