Debris destroys part but not really?

I’m having a weird issue with the debris system in roblox. I spawn a bullet and add it to the debris system with a lifespan of 3 seconds. I try shooting in the air (so it doesn’t hit anything) and after 3 seconds I can see that the bullet, which is a part, has been removed from workspace as expected. The weird thing however is that the part doesn’t seem to be fully gone. I add my bullets to a list to keep track of them an the weird thing is that even if the part is gone I can still use the list and get the position values from the part. Calling Destroy() on the object manually removes it properly but the debris system isn’t.

This is what my server code looks like: (modified to only have important parts for the question in it)

local function QuickRemove(tbl, index)
	local size = #tbl
	tbl[index] = tbl[size]
	tbl[size] = nil
end

local function moveBullets()
	for i, bullet in pairs(bullets) do
		print(bullet.Position)	
	end
end

game.ReplicatedStorage.RemoteEvents.RequestShot.OnServerEvent:Connect(function(plr, cframe, velocity)
	print(bullets)
	
	-- Create a bullet
	local bullet = replicatedStorage.Common.Models.Bullet:Clone()
	bullet.Parent = game.Workspace
	bullet.CFrame = cframe
	bullet:SetAttribute("Velocity", velocity)
	bullet:SetAttribute("Owner", plr.UserId)
	
	-- Add to debris for automatic cleanup
	debris:AddItem(bullet, 3)
	
	-- Add the bullet to the end of the table
	bullets[#bullets + 1] = bullet
end)

While Instance:Destroy() removes the object, you need to set any references of it to nil before it is removed from memory. So you must also remove it from the table, or not put it in the table in the first place.

Edit: just to explain it properly, destroying an Object sets the parent to nil and locks the parent to nil and that’s it. If there’s still a reference, you must set the reference to nil.

2 Likes

Ah, that makes sense, is there a way to check if the debris system has removed it?

I’m guessing this is what the lua garbage collector looks for when it’s searching for memory to clear?

1 Like

Just check the parent and see if it’s nil.

The garbage collector makes sure there is no reference to an object, then it will remove it.

2 Likes