Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Difference between FindFirstChild and WaitForChild?

Asked by 9 years ago

I'd like to know what the difference is, and when I should use which one.

0
FindFristChild will return nil if it's not found, WaitForChild yeilds the script so it won't continue until it's found. GoldenPhysics 474 — 9y

1 answer

Log in to vote
3
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
9 years ago

See here


Difference parent:WaitForChild(name) parent:FindFirstChild(name) parent[name]
Timing waits as long as needed instant instant
When not found waits as long as needed returns nil errors

If you are certain the object exists

If you know a child exists, you should not use either :WaitForChild or :FindFirstChild, you should use parent[name], e.g.,

Example: . and []

local obj = workspace["Brick"]
-- or equivalently
local obj = workspace.Brick

Only do this when you know the object exists. If the object does not exist, your script will error and stop running.

If the object may not exist

... and someone else is making it

If you are certain that the object will exist after a short time (e.g., someone else is in the process of making it for you -- the character is spawning and you are waiting for their Head, or you are waiting for a PlayerAdded script to add the "leaderstats" object to the player)

then you should use :WaitForChild. It cannot return nil and it cannot error. It will return the object as soon as it exists. Caveat: If an exist object is renamed to the name you asked for, then it will not realize it exists.

In particular, that means you can't use Instance.new("Part", parent) because it will be added with the name "Part" rather than the name you are waiting for.

Example: :WaitForChild

local player = game.Players.LocalPlayer

-- (there is another script that adds leaderstats to new players)

local leaderstats = player:WaitForChild("leaderstats")

... and you are making it

Maybe you're giving the player something, but you are making sure they don't already have one. In this case, you don't want to wait until they have it, because it's your job to give it to them.

We can check it if exists using :FindFirstChild. (You cannot do this with :WaitForChild because :WaitForChild never returns nil -- it just waits)

if player.Backpack:FindFirstChild("Sword") ~= nil then
    print("You already have a sword!")
else
    sword:Clone().Parent = player.Backpack
    print("You get a new sword")
end

.. and no one is making it

For the same reason as above, if you have no expectation that any other script will add the object, then you should not wait for that to happen.

-- start burning if anything burning touches me
if hit:FindFirstChild("Fire") then
    Instance.new("Fire", script.Parent)
end
Ad

Answer this question