FindFirstChild vs. WaitForChild

I’ve seen a lot of people use FindFirstChild() and WaitForChild() interchangeably, but I want to know what the difference between them is. What do they do?

Thanks in advance!

2 Likes

FindFirstChild simply finds the first thing with the given name of the first parameter. Usually you’d use this if you know 100% that the instance already exists when that line of code will run.

WaitForChild is different in the fact it will wait for something with the parameter name to exist. It won’t run the rest of the script until that actually exists. Useful if you’re unsure if the specific thing is there or spawned in or replicated quite yet.

Here is an example, as my explanation kinda sucks. Let’s say I have this script in the game.

task.wait(10)
local newPart = Instance.new("Part", workspace)

The script above will wait 10 seconds before spawning a part in workspace. If I have some code in another script which executes before this 10 second however, the following will occur:

workspace:FindFirstChild("Part") -- under the assumption this line fires before the part is replicated, this will error.

workspace:WaitForChild("Part") -- this will stop the script until it finds the part, thus waiting until the original line is fired.

Hopefully that helps. I left out a bit of information which can be found on the wiki page such as the other parameters, but I’m sure someone else can explain those more in depth if you’d like more info!

5 Likes

Should note that WaitForChild() will eventually time out, so still be careful

2 Likes

To add to this, FindFirstChild is only needed for conditional statements and iterative single-target searches.

if not workspace:FindFirstChild('Part') then
	print('a')
end
if not workspace['Part'] then
	print('b')
end

The first will print a, but the second will error. (Assuming “Part” doesn’t exist as a child of “Workspace”.)

FindFirstChild also has a secondary function if set to true:

workspace:FindFirstChild('Part',true)

This will search all descendants of “Workspace”, for an instance named “Part”, instead of just the direct children of “Workspace”.

WaitForChild obviously works as stated above, it yields until said instance is found. It also has an extra variable for attempts.

1 Like

The name says it. FindFirstChild Finds the child and WaitForChild waits for the child

1 Like

WaitForChild yields the current thread, and will throw an infinite yield if it can’t find the passed object, or it doesn’t exist. FindFirstChild will just return nil, and possibly error. No yielding! That’s basically the difference in a nutshell, lol. :grin:

1 Like