Car Spawner: Remove Old Car, When a New One is Spawned

Hello, I am working on a Car Spawner, however can’t seem to figure out a way to remove the old car, when a new one is spawned by the same player. Essentially, I am looking for a way for when a car is spawned/model is cloned, delete/destroy the player’s old vehicle.

I assume this question may have been asked before, so if it has, feel free to drop the link below, thanks!

1 Like

Just save the car as a variable in your script whenever the player spawns a car, like so

local cars = {}
local function spawnCar(plr,car)
    if (cars[plr] ~=) nil then -- checks if player has a spawned car
        cars[plr]:Destroy()  -- destroy the old car
    end
    local newCar = car:Clone() -- put your car spawning code here
    cars[plr] = newCar
end
3 Likes

Yeah piggy backing off what EmeraldLimes said you could just make a table with the cars in it and check if there are others or just make a folder that the car spawns in and loop through it to find pre existing cars

1 Like

To add on to this like @EmeraldLimes said above, you can additionally save the player who spawned it as a variable in case you might need it later.

1 Like

I’d hate to be the one to bump conversations, but I had a few questions;

So, I was looking for one of these too, But I had a concern. Where It says “your code here” are we putitng our car spawner code on that exactly line? If so, I think LUA is indent sensitive, so How would you indent without breaking the whole script?

And, Would we put this script into the button thats spawning the car? I’m using a GUI, so I’m curious.

(If I spelled something wrong, I apolgize. I’m on IPad.)

local cars = {}
local function spawnCar(plr,car)
    if (cars[plr] ~=) nil then -- checks if player has a spawned car
        cars[plr]:Destroy()  -- destroy the old car
    end
    local newCar = car:Clone() -- put your car spawning code here
    cars[plr] = newCar
end