API:Class/Instance/WaitForChild

WaitForChild

Function of Object Icon.pngInstance
Ref<Instance> WaitForChild (
    string childName,
    double timeOut
)
Parameters:
  1. childName
  2. timeOut

Returns: Ref<Instance>
Description: Yields the current thread until a child with the given name is found, then returns the child.

If the timeOut parameter is specified, this function will time out and return nil if timeOut seconds elapse without the child being found.

Notes

  • If a call to this function exceeds 5 seconds without returning, and the timeOut parameter isn't specified, then a warning will be printed to the output stating that it may never terminate with a stack-trace to the line that called it.
  • WaitForChild will act either as a regular Function or a Yield Function based on whether the child exists at the moment of calling or not. If the child exists when the function is called, then WaitForChild will not yield. Otherwise it will.
  • When working on LocalScripts, it is recommended to always use WaitForChild to access children (instead of other access functions such as the dot operator or FindFirstChild) so that the script is resilient to any loading issues. If there are circumstances where it is known for certain that the instance has already replicated to the client, then the code can be optimized to use the dot operator instead of WaitForChild.

Example

The following code waits for an instance named "Part" to be added to Workspace.

local part = Workspace:WaitForChild("Part")
print(part.Name .. " has been added to the Workspace")