Roblox objects and events, lesson 22
Finding objects safely
Goal: Look for an object without crashing when it is missing.
about 5 min3 practice exercises
workspace.Gate works when the gate is there. If it is not, because someone renamed it or it has not loaded yet, your script stops with an error.
Two functions make this safe.
FindFirstChild looks for a child by name and gives you nil if there is none. Test the result before using it:
local gate = workspace:FindFirstChild("Gate")
if gate then
gate.CanCollide = false
else
warn("No Gate in Workspace")
end
warn works like print but shows in orange, which makes problems easy to spot in Output.
WaitForChild pauses the script until the child exists, then returns it. Use it for things that will exist but might not be ready yet. This matters most on the player's device, where the world arrives piece by piece:
local gate = workspace:WaitForChild("Gate")
The rule of thumb: WaitForChild when it should be there soon, FindFirstChild when it might not exist at all.
To go through everything inside an instance, use GetChildren, which gives you an array:
for _, child in workspace.Coins:GetChildren() do
print(child.Name)
end
Sources
Checked against Roblox's documentation on . The lesson is in our own words; these pages are the source of truth.