I was following a tutorial on Youtube, and I saw WaitForChild instead of something like script.Parent, and I wondered, what is better to use? And if they are both useful, what times do you use one and the other one?
Depends, WaitForChild would be needed if this script is running before the game has finished loading yet. It would also be needed if, say, there’s another script that’s parenting a part to workspace and you have to use waitForChild while referencing it in this script to make sure this script would work even if it ran before the other one.
Hey dude, I was curious about this question. script.Parent and WaitForChild don’t really overlap uses. But they are both important in different scenarios. So hope you find this useful.
script.Parent is a relative path, it refers to the parent object the script is under. So if you have a script in serverScriptService, it will point to roblox’s serverScriptService object.
WaitForChild is used when you want to get a child object, and by name it will wait if that object doesn’t exist when the code first runs. This is useful when waiting on a object when it hasn’t loaded yet.
But the key difference, is script.Parent grabs a parent object; WaitForChild grabs a child object. So here’s two cases where you’d use them.
Case1- Local script in ScreenGui
local gui = script.Parent -- If a script runs; it has a parent object.
local button = gui.Button -- If the script is loaded, it's siblings should also be loaded.
Case2- Local script in StarterPlayerScripts
local player=game:GetService('Players').LocalPlayer -- Localplayer, always exists on client scripts
local gui=player.PlayerGui:WaitForChild('ScreenGui') -- ScreenGui objects loads when the character spawns, so we need to wait because this script runs before that happens
local button=gui.Button -- ScreenGui exists, so its children should also exist