Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

How to make a car despawn after you spawn in another one? (Like in vehicle Simulator)

Okay so I just made this game that was really hard to make because I'm super new to scripting and I made a GUI that spawns cars. Every time I spawn a car it spawns behind me. If I want to spawn a different car it spawns behind me but the other is still there. How do I get rid of the old car. Here is an example. https://gyazo.com/13017587aa492f38b874cd969b59508d

2 answers

You could try using a variable that references the old car, and each time the car spawns the old one is deleted.

It would look something like this:

local currentCar --creates new variable that is "nil" (doesn't have a value)
script.Parent.MouseButton1Down:Connect(function()
	if currentCar then -- if there already is a car
		currentCar:Destroy() -- then destroy it
	end
	local clone = car:Clone()
	currentCar = clone
end)

This is just an example so you would need to create the rest of the script by yourself.

this will only do things on the client side, lets move it to the server

local script

script.Parent.MouseButton1Down:Connect(function()
game.ReplicatedStorage.spawncar:FireServer()
end)

server script

game.ReplicatedStorage.spawncar.OnServerEvent:Connect(function()
if game.Workspace:FindFirstChild("car name") then
game.Workspace.car name:Destroy()
else
game.ServerStorage.car name:Clone().Parent = game.Workspace
end
end)

This discussion is preserved as it was. New answers, comments, and votes are closed.