Wait until loop has iterated through all descendants of a certain class

I’m attempting to make a script that Iterates through ALL descendants of the script, and once it does. It preloads all animations. I’m trying to make this to make sure that Content Provider iterates over EVERYTHING. Please let me know if it is not necessary.

local ContProv = game:GetService("ContentProvider")

local assets = {}
local loadednum = 0
for _,v in pairs(script:GetDescendants()) do
	if v:IsA("Animation") then
		table.insert(assets, v)
		loadednum += 1
	end
end

local callback = function(assetId)
	print("PreloadAsync() resolved asset id of:", assetId)
		
end
	
if loadednum == script:GetDescendants() then
	ContProv:PreloadAsync(assets)
end

In my experience the for loop already yields, until it has went thru all provided items. You can add at very start:

if not game:IsLoaded() then
   game.Loaded:Wait()
end

This will yield until everything important is loaded.

2 Likes

This script is okay except for a few parts. I’d just tweak it a bit to fit your query

local ContProv = game:GetService("ContentProvider")

local assets = {}
local loadednum = 0
for _,v in pairs(script:GetDescendants()) do
	table.Insert(assets, v) --- You did say EVERYTHING
	loadednum += 1
end
	
if loadednum == #script:GetDescendants() then
	ContProv:PreloadAsync(assets)
end
1 Like