How would I repeat a segment of code after a model gets destroyed?

Since I’m creating an ore system, I have everything else running fine apart from the last feature which is taking some time to figure out. What I wish to do is run the segment of code which is responsible for randomly spawning ores whenever an ore is “mined” after a certain delay so as the spawning seems more natural. I’ve tried returning and descendantsremoving but I have yet to receive any solution. Any help is most appreciated, and below will be the code that I’ve already written.

local function OreSpawn()

	local OresToSpawn = {}


	for i = 0, InitializeOre, 1 do
		task.spawn(function()
			local result = Roll()

			table.insert(OresToSpawn, result)

		end)
	end

	for Index, Ore in OresToSpawn do



		local Index : number = math.random(#spawnBricks)
		local Chosen : Part = spawnBricks[Index]
		local FoundLocation = Spawns:FindFirstChild(Chosen.Name)

		if Chosen.Occupied.Value == true then
			repeat
				wait(1)
				Index = math.random(#spawnBricks)
				Chosen = spawnBricks[Index]
				FoundLocation = Spawns:FindFirstChild(Chosen.Name)
			until Chosen.Occupied.Value == false
		end
		
		if Ore == "Rock" then
			local rockClone = Ores[1]:Clone()
			rockClone.Parent = FoundLocation
			rockClone:PivotTo(FoundLocation.CFrame)
			rockClone.Parent.Occupied.Value = true
		elseif Ore == "IronOre" then
			local ironClone = Ores[2]:Clone()
			ironClone.Parent = FoundLocation
			ironClone:PivotTo(FoundLocation.CFrame)
			ironClone.Parent.Occupied.Value = true
		elseif Ore == "GoldOre" then
			local goldClone = Ores[3]
			goldClone.Parent = FoundLocation
			goldClone:PivotTo(FoundLocation.CFrame)
			goldClone.Parent.Occupied.Value = true
		elseif Ore == "AzureOre" then
			local azureClone = Ores[4]:Clone()
			azureClone.Parent = FoundLocation
			azureClone:PivotTo(FoundLocation.CFrame)
			azureClone.Parent.Occupied.Value = true
		end	
	end
end


Players.PlayerAdded:Connect(OreSpawn)
1 Like

Put the code you want to repeat in a function (OreSpawn here I think) and just call it when the model gets destroyed

How would I look through the children of each spawn part, firing when a boolvalue is set to false?

Of course after the function is run once, so as to not disturb the initializing of ores.

You can catch whenever an instance gets destroyed with the Instance.Destroying event.

for index, spawnPart in spawnParts do
	for index2, child in spawnPart:GetChildren() do
		if child:IsA("BoolValue") and not child.Value then
			-- run code here
		end
	end
end