This is a similar feature request dealing with the same issue, however it’s based around a different solution. I thought it’d be better if these two things were separated, mainly due to the detail of this post.
As a scripter, I find it really frustrating having to write :WaitForChild("ChildName")
all the time, for things that I should just be able to access error-free. What is even the point of being able to do Object.Child
if it breaks most of the time?
I propose a different solution that I’ve seen work fine on a different engine, and that won’t break any older scripts.
Godot Engine has a function _ready()
that runs when the object the script is attached to and all of its children are loaded. It also has a keyword onready
added to variable assignments so that it will assign the variable when said condition has been reached.
Example of ready implementation in Godot
onready var child = get_node("child")
func _ready():
child.connect(signal, func) # hook up a listener
Lua version (for understanding):
local Child = script:WaitForChild("Child")
Child.Signal:Connect(Func)
I suggest all scripts have some way to know when an object and its children are fully loaded. A signal, and possibly a bool property, would be a good solution to this IMO.
Example usage
-- LocalScript inside a ScreenGui
local Gui = script.Parent
-- A ready signal
Gui.Ready:wait()
-- A ready property
repeat wait() until Gui.IsReady
-- Do stuff that could cause an error in the current engine
local Frame = Gui.Frame
local Button = Gui.Buttons.Button1
I can see lots of use cases for this. Not only would this make GUI scripting easier and quicker, it would also allow us to just wait for something to load (e.g. a large map cloned into workspace – goodbye custom map loader system!).
And since we’re just adding stuff, there’s backwards compatibility.
From a design perspective, I believe WaitForChild should be used a lot less, too (about the same amount as FindFirstChild). It’s a method that’s supposed to be for waiting for things that may not be there yet, or at all – and yet it gets used primarily for things we know are there and for things that should be there now.
Thanks