Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Why should I use :WaitForChild instead of .AmountOfOrbs?

Asked by
Cowgato 33
2 years 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
            end

1 answer

Log in to vote
0
Answered by 2 years ago
Edited 1 year 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, those will be the first assets replicated 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 itself proclaims 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 if you're inside of a localscript.

0
LORD. I did not expect to see you here. Ziffixture 6913 — 2y
1
Still alive :D ScriptGuider 5640 — 2y
0
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 2189 — 2y
Ad

Answer this question