Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Am I using :WaitForChild() incorrectly?

So I've been told many times that you should almost always use :WaitForChild() to reference children instead of using periods for safety.

So now when writing my scripts and if I need to reference children I always use WaitForChild, but it starts to get excessive and repetitive. For example,

game.Workspace:WaitForChild("Part"):WaitForChild("Object"):WaitForChild("Scr...

I'm wondering if I'm being too cautious or using :WaitForChild() clumsily, and if anyone could chirp in to correct me. :)

4 comments

0

There are some cases where you don't need WaitForChild. In your case, it is not required. There are objects that do need WaitForChild, such as the PlayerGui, PlayerScripts, and Backpack. Just a few examples.

0

yeah man, if the child referanced is confirmed to be there then use periods, only if you risk not having a child there do you use WaitForChild, although if the script starts up along with the server at the same time then you should be aware the child may not exist yet

0

So let's say I wanted to reference a TextButton located in a Frame inside a ScreenGui in the player. Would it be fine if I used :WaitForChild() just once? game.Players.Player1.PlayerGui:WaitForChild("ScreenGui")...etc ---- also it doesn't hurt to use :WaitForChild() all the time, right? It's only inconvenient.

0

You shouldn't use it if it's not required. If the LocalScript is a child of the TextButton, you'd have to wait for the script itself. It makes no sense waiting for an object that is the parent of a script.

1 answer

✓ Accepted answer

So for example, you would only use :WaitForChild(), if you're referencing a child, before the server fully connects. For example, you would do:

game.Players.PlayerAdded:Connect(function(plr)
plr.PlayerGui:WaitForChild("ScreenGui").Frame
end)

So you really only need to use WaitForChild(), if the code takes place when the server first starts. And as you see in my example, if you're listed children of what you waited for, you don't need to wait for that, as it's already loaded in because the parent was loaded in.

This discussion is preserved as it was. New answers, comments, and votes are closed.