I understand how to use Debris (service) to set a timer before a piece of debris is destroyed, by doing game:GetService('Debris'):AddItem(part, 10)
My question is, is there a way to add a maximum number of debris per server so that if an extra one is created, the oldest is destroyed? I understand I can create my own module to track this, but I would like to know if there is a built-in way.
you can do so by creating your own debris service. Debris service on its own isnt really customizable.
You would need to log the destroyed item in a table, and if the table length is greater than the max items, destroy the first entry in the table and shift everything down a number. Besides that, you could probably be able to get away with using task.delay to destroy the part.
I have made one, it’s object oriented and has it’s own destroy function and customisable queue, keep in mind I have not tested this yet
--[[
File name: QueuedDebris.lua
Author: RadiatedExodus (ItzEthanPlayz_YT, RealEthanPlayzDev)
Created at: October 4 2021
An object-oriented queued debris with it's own destroy function and customisable max queue
--]]
--// CLASS QueuedDebris
local QueuedDebris = {}
QueuedDebris.__index = QueuedDebris
--// function QueuedDebris:AddItem(item: Instance, lifetime: number?): nil
function QueuedDebris:AddItem(item: Instance?, lifetime: number?): nil
if self.__destroyed then return error("QueuedDebris already destroyed", 2) end
if #self.__queue > self.__maxItems then
local st = #self.__queue - self.__maxItems
for i = 1, st do
local item = self.__queue[self.__maxItems + i]
if item and typeof(item) == "Instance" and item.Parent ~= nil then
xpcall(item.Destroy, warn, item)
self.__queue[self.__maxItems + i] = nil
else
self.__queue[self.__maxItems + i] = nil
end
end
end
task.delay((lifetime or 0), function()
if item and typeof(item) == "Instance" then
xpcall(item.Destroy, warn, item)
end
end)
table.insert(self.__queue, item)
return nil
end
--// function QueuedDebris:AddItem(item: Instance, lifetime: number?): nil
function QueuedDebris:SetMaxItems(amount: number): nil
assert(typeof(amount) == "number", ("invalid argument #1 to 'SetMaxItems' (number expected, got %s)"):format(typeof(amount)))
self.maxItems = tonumber(amount)
return nil
end
--// DESTROYER QueuedDebris:Destroy()
function QueuedDebris:Destroy()
self.__destroyed = true
for i, inst in pairs(self.__queue) do
if inst and typeof(inst) == "Instance" then
xpcall(inst.Destroy, warn, inst)
self.__queue[i] = nil
else
self.__queue[i] = nil
end
end
end
return {
--// CONSTRUCTOR
new = function(maxItems: number?)
return setmetatable({
__maxItems = tonumber(maxItems) or 1000;
__queue = {};
__destroyed = false;
}, QueuedDebris)
end,
}