Destroy a clone after new one is made

I am trying to clone a cart in 18 second intervals. Once it is cloned, however it should be destroyed after 3 minutes.

I have tried

-- while true do
	local cartCopy = game.ServerStorage.Cart:Clone()

	cartCopy.Parent = game.Workspace	

but of course, then it waits out the 3 minutes before cloning the next one. Any advice?

You can do this without yielding any code simply by using Roblox’s Debris.

Your fix would be:

local cartCopy -- this is done to create the variable
-- while true do
	cartCopy = game.ServerStorage.Cart:Clone() -- everytime the loop runs, it will set the variable to a fresh clone of the cart from ServerStorage

	wait(18) -- waits 18 seconds
	cartCopy.Parent = game.Workspace -- sets the carts parent to the workspace
    game.Debris:AddItem(cartCopy,180) -- this will destroy it after 3 minutes without yielding any code

Let me know if you have any more problems!

If you wanted to use Debris multiple times:

  1. Set a variable for Debris Service
local debris = game:GetService("Debris")
  1. Instead of game.Debris:AddItem(), you could simply do debris:AddItem()
1 Like

Small tip, use task.wait() over wait().


Thank you, this worked. I did not kn ow about Debris

The above answer worked, but now I’ve learned something new. Thank you!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.