Log in to vote

Why should I use :WaitForChild instead of .AmountOfOrbs?

Asked by
Cowgato 33
20 days ago

What I am trying to say, is why should I use workspace:WaitForChild("AmountOfOrbs") instead of game.workspace.AmountOfOrbs?

--AmounOfOrbs is a numbervalue in workspace btw--

if workspace:WaitForChild("AmountOfOrbs").Value >= 3 then
                workspace.Door.CanCollide = false
        workspace.Door.Transparency = 0.25

1 answer

Log in to vote
Answered by 20 days ago
Edited 20 days ago

It depends on the location of your script and what kind of script you're using. When you first join a game, the server first looks inside of the ReplicatedFirst service to see if it contains any assets. If it does, they are the first assets that will be sent to the client.

Therefore, if you have a script running inside of ReplicatedFirst, that code will run before the workspace assets have loaded into your game and thus you should use WaitForChild on them.

As a rule of thumb:

Always use WaitForChild when accessing objects from inside a localscript. This is because localscripts are replicated to users dynamically and their time of execution may be unpredictable. ROBLOX themselves proclaim that the order in which content arrives to the client is unpredictable. You can read more about this here.

When NOT to use WaitForChild

It will never hurt you to use WaitForChild, but it is unnecessary in the following circumstances:

  • Using WaitForChild to access child or descendant objects, such as script:WaitForChild('module')
  • Using WaitForChild in a server-side script for static objects (objects that are not dynamically generated in).
  • Chaining WaitForChild calls, such as: object:WaitForChild('child_a1'):WaitForChild('child_b1'):WaitForChild(...)

There may also be more container services within ROBLOX that alter the order in which content is sent to the client, so that may be worth digging into.

My Recommendation

My personal recommendation would be to avoid using WaitForChild unless you're running into attempt to index nil value errors, or you're inside of a localscript.

LORD. I did not expect to see you here. Ziffixture 6913 — 20d
Still alive :D ScriptGuider 5579 — 20d
He prob made this question from my answer in his previous question. I used the :WaitForChild() just incase if it runs on a "attempt to index nil value" but thx for giving me new knowledge T3_MasterGamer 845 — 19d

Answer this question