How to wait for Children inside Folder to Load

Hi there all,

I wanted to make it so it loops through a folder of parts at the start of the game, but it loops through before the folder contents have even loaded. This results in it looping through nothing.

Here is an example:

local Folder = workspace.Folder

for _, v in Folder:GetChildren() do
	print(v.Name)	-- Never Prints
end

And it only prints when I do task.wait(1), but doing something like that is not reliable at all.
Thanks a lot for your help!

Folder.ChildAdded:Once(function()
wait(2)
	for _, v in Folder:GetChildren() do
		print(v.Name)	-- Never Prints
	end
end)

A crude fix, but this should work.

1 Like

Why wouldn’t u just use ChildAdded on the folder then whenever a child is added to said folder u loop through it. Or u dont even have to loop just do the straight out code such as

local Folder = workspace.Folder

Folder.ChildAdded:Connect(function(child)
       print(child.Name)
       -- do code here
end)
1 Like

I think the best way to be sure to initialize all instances of your folder is the way below:

-- Variables
local Folder = workspace.Folder

-- Functions
local function InitializeInstance(instance)
	print(instance)
end

-- Initialize
for _, v in Folder:GetChildren() do
	InitializeInstance(v)
end

-- Connections
Folder.ChildAdded:Connect(InitializeInstance)

We initialize all the instances already present and we wait for others to be added.
Let me know if this helped you. You can also ask me any questions if you have any.

2 Likes

ignore previous post- reading is hard

1 Like

If server: build your code base that acknowledges the data structure. I doubt this is server code though.

If client: write an attribute to the model/folder that contains the total amount of instances. In your code, continue running GetChildren until the number meets or exceeds the attribute.

1 Like