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 []
1 | local obj = workspace [ "Brick" ] |
3 | 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
1 | local player = game.Players.LocalPlayer |
5 | 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)
1 | if player.Backpack:FindFirstChild( "Sword" ) ~ = nil then |
2 | print ( "You already have a sword!" ) |
4 | sword:Clone().Parent = player.Backpack |
5 | print ( "You get a new sword" ) |
.. 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.
2 | if hit:FindFirstChild( "Fire" ) then |
3 | Instance.new( "Fire" , script.Parent) |