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
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.
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.
It will never hurt you to use WaitForChild
, but it is unnecessary in the following circumstances:
WaitForChild
to access child or descendant objects, such as script:WaitForChild('module')
WaitForChild
in a server-side script for static objects (objects that are not dynamically generated in).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 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.