If you’re like me, your interfaces are both a) not built with Roact and b) have a whole lot of nested components. As a result, spamming UI scripts with WaitForChild
calls seems almost inevitable.
Last year I wound up making a function to deal with the never-ending pain, and I’ve had a fair amount of success with it so I think it’s worth sharing here. It works by accepting the object to start searching from, and then an object path as a string, the same way you would write it to normally reference an object. It also accepts an optional maxWait
parameter. Here’s an example(s?):
Example
local WaitForPath=require(game.ReplicatedStorage.WaitForPath)--assuming this is the place the module is stored
local player=game.Players.LocalPlayer
local interface=WaitForPath(player,"PlayerGui.Interface")
local superNestedCloseButton=WaitForPath(interface,"MainMenu.Panels.SuperCoolPanel.Options.Close") --returns the button
local otherButtonButWithMaxWait=WaitForPath(interface,"SecondMenu.Panels.SuperCoolerPanel.Options.MaybeClose",5)--returns button, or nil after 5 seconds
Usage
Instance WaitForPath(Instance target,string path[,number maxWait])
Source
Here’s a .rbxmx file you can drop into your game:
WaitForPath.rbxmx (3.2 KB)
And here’s the source if you’d rather just copy-paste it into a ModuleScript:
local BAD_ARG_ERROR="%s is not a valid %s"
local function WaitForPath(target,path,maxWait)
do --error checking
local tt=typeof(target)
local tp=typeof(path)
local tm=typeof(maxWait)
if tt~="Instance" then error(BAD_ARG_ERROR:format("Argument 1","Instance")) end
if tp~="string" then error(BAD_ARG_ERROR:format("Argument 2","string")) end
if tm~="nil" and tm~="number" then error(BAD_ARG_ERROR:format("Argument 3","number")) end
end
local segments=string.split(path,".")
local latest
local start=tick()
for index,segment in pairs(segments) do
if maxWait then
latest=target:WaitForChild(segment,(start+maxWait)-tick())
else
latest=target:WaitForChild(segment)
end
if latest then
target=latest
else
return nil
end
end
return latest
end
return WaitForPath
Bits
- If the path can’t be found within the allotted
maxTime
, the function will returnnil
. - If the path doesn’t exist and no
maxTime
has been set, the function will yield forever. - I’ve poked and prodded this function a few different ways since I made it, so although it works for me, depending on how you use it you might run into some janky behavior. Chipio IndustriesTM is not liable for any jankTM you encounter while using this function.
- Do not read the .rbxmx