Disconnect connection when all images are loaded

You can write your topic however you want, but you need to answer these questions:

  1. What do you want to achieve? Keep it simple and clear!
    I inserted 60 images into my game and want to preload all of them when a player joins.
  2. What is the issue? Include screenshots / videos if possible!
    I got over the problem of DecalID to ImageID but there’s one last thing. I need to make all images visible to load them and then make them invisible when they finish loading. I achieved this by using RenderStepped. However, it won’t stop making the images invisible after they finished loading so I can’t use them.
  3. What solutions have you tried so far? Did you look for solutions on the Developer Hub?
    The backup plan is using a dictionary that contains 60 images’ names as keys associated with their IsLoaded value but this might take a while.

Heres the code:

-- LocalScript(Images are separated into 2 categories in 2 folders)
local conn
conn = runs.RenderStepped:Connect(function()
	for _,image in pairs(fold1:GetChildren()) do
		if image.IsLoaded == true then
			image.Visible = false
		end
	end
	for _,image in pairs(fold2:GetChildren()) do
		if image.IsLoaded == true then
			image.Visible = false
		end
	end
end)

Any help is appreciated. Thanks in advance.

One simple, but maybe ugly, solution would be to do something along the following:

local conn
conn = runs.RenderStepped:Connect(function()
    local all_loaded = true -- Assume all is loaded
	for _,image in pairs(fold1:GetChildren()) do
		if image.IsLoaded == true then
			image.Visible = false
		else
            all_loaded = false -- All is not loaded
        end
	end
	for _,image in pairs(fold2:GetChildren()) do
		if image.IsLoaded == true then
			image.Visible = false
		else
            all_loaded = false -- All is not loaded
        end
	end
    if all_loaded then -- Since it will stay true *unless* something isn't loaded
        conn:Disconnect() -- this will only trigger if all is loaded
    end
end)

This is a lot more complicated than simply doing a :WaitForChild() so I’m guessing that’s not applicable here?

edit: fixed comment in code

A WaitForChild() would significantly slow down the script so using a variable is probably a better idea, and much simpler than my backup plan. Thanks for the solution.

1 Like

Disconnect the connection after the loops because that won’t be run until they are completed

table.foreachi(fold2, function(_, image)
	table.insert(fold1, image)
end)
fold2 = nil

local conn
conn = runs.RenderStepped:Connect(function()
	for _, image in ipairs(fold1) do
		if not image.IsLoaded then
			return
		end
	end
	conn:Disconnect()
end)

This is a very elegant solution, however would it not be better to create a new variable for the combined tables?

If fold2 is being used elsewhere in the script, yes.

You’d need to iterate over fold1's items and insert them into that table too though.