Better alternative to WaitForChild

Got it! I just instantly saw this and instantly was thrown into a second-hand panic, lol.

1 Like

Does that mean you serialize literally everything you need a reference to just to avoid WaitForChild?

I assume @Tomarty means that all of their game’s logic is written in ModuleScript instances whose execution is deferred once all required objects are initialized and replicated, managed by one Script instance on the server and one LocalScript instance on the client.

If this is the situation, WaitForChild being used in its traditional case of ensuring an instance has replicated before interacting with its reference can be phased out; with a perfect implementation, replication at that point is a guarantee given the scenrio.

1 Like

This is accurate. When a game has multiple Scripts / LocalScripts, it is not necessarily known what order they will be run in. If, for example, you wanted to use _G for quick access to immutable utility functions, and need to ensure the local player exists, you might use code like this:

while not _G.Utility do
    wait()
end
local Players = game:GetService("Players")
while not Players.LocalPlayer do
    Players:GetPropertyChangedSignal("LocalPlayer"):Wait()
end

While usage of _G is debatable, wait-for-everything design becomes difficult to manage in large projects, because scripts need to snap into place over time, yielding back and forth; With ModuleScripts, you can simply run code when what it needs is known to be ready, or even create instances proactively when they are needed (instead of waiting for them.)

This is more difficult to apply within the context of classic Roblox characters / guis. We are all used to creating tools that have individual scripts that are destroyed when no longer needed, waiting for objects in default characters, and never knowing what gui instances will be replicated, but this is all holding us back from creating huge stable experiences:

  • Multiple server scripts for every player does not usually scale well with large servers.
  • Scripts may error if they yield while setting up an player / character / object and the corresponding player leaves.
  • If a tool creates an instance and adds it to the workspace with the intent to destroy it later, it will leak that instance if the tool is destroyed before it cleans it up.

For anyone making a large game, I highly recommend using a ‘Maid’ class to track connections, and consider making a custom scheduler that can be disconnected from instead of using wait. It’s such a headache working with tons of Scripts / LocalScripts that run their own threads that are created / destroyed on a whim.

2 Likes

if you’re defining self, you might as well just do

local toWaitChild = game.WaitForChild;
toWaitChild(workspac, 'Name'); 

no?

1 Like