When doing :GetChildren at the start of a script will all children be accounted for or will some be potentially unloaded?

I’ve never run into problems with doing GetChildren at the start of scripts, however I do not know if it could potentially cause issues

I’d assume not due to several factors such as

  1. GetChildren is not a yielding function
  2. Functions like WaitForChild are commonplace in scripts, waiting for the hierarchy to fully load in

Does anyone have input on this topic?

2 Likes

From my understanding, if the object that you’re referencing contains static Instances/Instances that are already there prior to runtime, they’ll be accounted for.

However, if any Instances are added or removed from the object (during runtime) after calling :GetChildren() on it, the table will not be updated to account for that because the variable was initialized prior to those additions.


For example, this would NOT print the updated table:

local Item = workspace.Baseplate
local currentItems = Item:GetChildren()

while true do
	wait(3)
	print(currentItems)
end

While this would:

local Item = workspace.Baseplate

while true do
	wait(3)
	
	local currentItems = Item:GetChildren()
	print(currentItems)
end

I ran into this problem when I needed to store the parts of a player character in a table. Consequently, the GetChildren method would sometimes miss some parts (due to loading). For as far as I know, there is not really an elegant alternative to GetChildren. What I have done in the past is:

  • Use WaitForChild anyway
  • Wait until an instance has a certain number of children (not recommended)

GetChildren returns an array of the children currently under a directory. It is asynchronous, and not binded to an event.

However, you can keep it updated. See the example code below:

-- Assuming "Thing" is a valid instance already defined
local Children; -- Create the variable

local function UpdateChildrenTable()
   Children = Thing:GetChildren()
end

Thing.ChildAdded:Connect(UpdateChildrenTable)
Thing.ChildRemoved:Connect(UpdateChildrenTable)

UpdateChildrenTable()

Hope this helped.

2 Likes

Some sample code:

local function waitForChildren(parent, names)
    local children = {}
    for _, name in pairs(names) do
        table.insert(parent:WaitForChild(name))
    end
    return children
end

local parts = waitForChildren(character, {
    'Head',
    'HumanoidRootPart',
    'UpperTorso',
}