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

Why should I use :WaitForChild instead of .AmountOfOrbs?

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

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.

3 comments

0

LORD. I did not expect to see you here.

1

Still alive :D

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

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