Instance can't be deleted or replaced with nil

My function:

function DeleteObject(Object)
	
	if Object ~= nil then
		repeat
			Object:Destroy()
			Object = nil
			game["Run Service"].RenderStepped:Wait()
		until Object == nil
		if Object ~= nil then
			DeleteObject(Object)
		end
		
	end
end
if Box == nil then
			
			Box = script.Selection:Clone();
			Box.Parent = ToParent;
			Box.Adornee = ToParent;
			Box.Enabled = true;
			
		end
if Box ~= nil then
		
		Box:Destroy()
		
		if Box ~= nil then

			DeleteObject(Box)
			
		end
		
	end

image
It is suppose to delete and turn to nil but doesnt

When you destroy an instance, it still stays in memory because it still has a reference, that being the variable it was assigned to. You have to immediately clear out the variable to fully “delete” it.

This code below doesn’t clear the Box variable, which is why the DeleteObject function runs.

And that DeleteObject function is basically useless. Object is just a local variable of the function storing the instance, and setting that variable to nil will only affect the scope of the function.

So the correct way to do this is to immediately clear the variable storing the instance after you :Destroy() it.

Box:Destroy()
Box = nil
1 Like