Current features:
- Canceling
- Usage with Non Instance (RBLXScriptConnection and tables)
- Adding an Array of Items instead of just one at a time
- Overriding lifeTime
- A Callback for when the Item has been Destroyed
Source Code
--[[
@game/ReplicatedStorage/Debris2
Debris2;
--]]
local Debris2 = {
Instances = {}
}
--| SERVICES:
local RunS = game:GetService("RunService")
local Heatbeat = RunS.Heartbeat
--| MODULES:
--| VARIABLES:
local Instances = Debris2.Instances
--| TABLES:
local Connections = {}
local ValidTypes = {
["Instance"] = "Destroy",
["table"] = true,
["RBXScriptConnection"] = "Disconnect",
}
local METHODS = { -- add any Custom Destroy/Remove/Clear/CleanUp methods here
"Destroy",
"Disconnect",
"destroy",
"disconnect",
}
--| META TABLES:
--| FUNCTIONS:
local function removeItem(typeOf,object)
if typeOf == "Instance" then
pcall(object.Destroy,object)
elseif typeOf == "RBXScriptConnection" then
pcall(object.Disconnect,object)
else
for _,v in ipairs(METHODS) do -- _, v: method name
if object[v] then
pcall(object[v], v)
break
end
end
end
end
local function addDebris(object,lifeTime)
local typeOf = typeof(object)
assert(ValidTypes[typeof(object)])
assert(typeof(lifeTime) == "number")
if (not Instances[object]) then
table.insert(Instances,object)
end
Instances[object] = {
["lifeTime"] = lifeTime,
removalTime = tick() + lifeTime,
-- Destroyed = nil, -- Destroyed: callback Function
Cancel = function() -- remove references and disconnect Hearbeat
Connections[object]:Disconnect()
table.remove(Instances,table.find(Instances,object))
Instances[object] = nil
end,
["Instance"] = object,
}
local debris = Instances[object]
Connections[object] = Heatbeat:Connect(function()
if debris and tick() >= debris.removalTime then
if debris.Destroyed then
debris.Destroyed()
end
debris.Cancel()
removeItem(typeOf,object)
end
debris = Instances[object]
end)
return Instances[object]
end
--| METHODS:
function Debris2:AddItem(item,lifeTime) -- item: (Instance, table, RBXScriptConnection), lifeTime: number
return addDebris(item,lifeTime)
end
function Debris2:AddItems(arrayOfItems,lifeTime) -- arrayOfItems: (Instance, table, RBXScriptConnection), lifeTime: number
for _,v in ipairs(arrayOfItems) do -- _, v: Instance
addDebris(v,lifeTime)
end
end
function Debris2:GetAllDebris()
return Instances
end
Debris2.getAllDebris = Debris2.GetAllDebris
function Debris2:GetDebris(instance)
return Instances[instance]
end
Debris2.getDebris = Debris2.GetDebris
--| SCRIPTS:
-- return:
return Debris2
- Ready to ship
- Needs improvements (reply with improvement!)
0 voters
I probably will need help with Documentation & Github, as this is my first Open Source project