How To destroy specific objects?

Hello! i am making a racing game where you can change your car anywhere by pressing “C” and choosing a car. i have a code that should do that but i dont want you to have more than 1 car at a time. is there a way to destroy all other cars when you spawn a new one?
i have tried to do

Destroy (HoverCar);

or

Destroy (Truck);

but it doesnt work. please could somebody tell me what i did wrong?

code:
var HoverCar : Transform;
var Truck : Transform;
var script : Camera;

function OnGUI () { 

	if (Input.GetAxis("C")){
			
			if (GUI.Button(Rect(10,70,100,30),"Hover Car")){
			Destroy (HoverCar);
			Destroy (Truck);
           	Instantiate (HoverCar, Vector3 (542.78, 1.3, 312.64), Quaternion.identity);
			script = GetComponent(Camera); script.enabled = false;
            }
            
            if (GUI.Button(Rect(10,100,100,30),"Truck")){    
			Destroy (Truck); 
			Destroy (HoverCar);     
            Instantiate(Truck, Vector3 (542.78, 1.3, 312.64), Quaternion.identity);
            script = GetComponent(Camera); script.enabled = false;
            }
            
		}
	}

HoverCar and Truck are transforms? Well, I think that you need to save the GameObject that you Instantiate and destroy this GameObject, then Instantiate a prefab. What I’m watching in your code is that you are destroying the same reference you are gonna instantiate.

Hi :slight_smile:

There are different solutions but here is the one that comes to me:

  • Add a “car” tag to your cars/trucks

  • Find all the the cars with GameObject.FindGameObjectsWithTag (Unity - Scripting API: GameObject.FindGameObjectsWithTag) that will give an array of all the cars/trucs with the good tag

  • Destroy the objects in the array

  • Instantiate your new car

  • Have fun and drive carefully