Need help making a queue system for troop spawning

  1. What do you want to achieve?
    Make a queue system for troop spawning:
  • Stopping when the spawn building is deleted (adornee).
  • Being able to spawn troops in order.
  1. What is the issue?
    Troops don’t spawn in order and spawning doesn’t stop when the spawn building is deleted (adornee).
    https://streamable.com/ew6sdj

  2. What solutions have you tried so far?
    I’ve tried some solutions from this forum but they didn’t work or i didn’t understand them.

The script:

local queue = {}

function add_to_queue(unit)
	table.insert(queue, unit)
end

function remove_from_queue()
	return table.remove(queue, 1)
end

game.ReplicatedStorage.Spawn.OnServerEvent:Connect(function(player, unit, adornee, pFolder)
	local finished = pFolder.Finished
	--sanity checks
	repeat wait(0.1) until finished.Value == true
	print("lol")
	finished.Value = false
	run(unit, adornee, player, finished)
end)

function run(unit, adornee, player, finished)
	for i,v in pairs(queue) do
		--visual progress bar
		wait(unit:GetAttribute("Time"))
		finished.Value = true
		--spawn the troop
		remove_from_queue()
	end	
end

Add the following to your loop.
if not adornee.Parent then break end
for i,v in ipairs(queue) do
Use the ipairs iterator factory to iterate over arrays in order.

1 Like

The queue system is fixed, however troops won’t stop spawning whenever the building is deleted.

refined script:

local queue = {}

function add_to_queue(unit)
	queue[#queue+1] = unit
end

function remove_from_queue()
	return table.remove(queue, 1)
end

game.ReplicatedStorage.Spawn.OnServerEvent:Connect(function(player, unit, adornee, pFolder)
	--sanity checks
	add_to_queue(unit)
	
	while wait(0.2) do
		if not adornee.Parent then break end
		if #queue > 0 then
			for i,v in ipairs(queue) do
				local finished = pFolder.Finished
				repeat wait(.1) until finished.Value == true
				if not adornee.Parent then break end
				--visual loading bar
				finished.Value = false
				wait(5)
				finished.Value = true
				--spawn the troop
				if not adornee.Parent then break end
			remove_from_queue()
			end
		end	
	end
end)

Is adornee ever destroyed and/or parented to ‘nil’?

if the a building is sold or killed then It’s parented to ServerStorage and then destroyed instantly.

Add print(adornee.Parent) inside the loop.

I think it captures the building position before it’s deleted, but I’m not sure because I’m not on the computer right now