- Home /
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;
}
}
}
Does the rest of that code work? eg does it create a button and instantiate a different car? Because I think you need Input.Get$$anonymous$$ey("c") ins$$anonymous$$d of Input.GetAxis("c")
Answer by ShabihDesperado · Mar 31, 2015 at 07:39 AM
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.
Answer by KdRWaylander · Mar 31, 2015 at 10:22 AM
Hi :)
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
(http://docs.unity3d.com/ScriptReference/GameObject.FindGameObjectsWithTag.html) that will give an array of all the cars/trucs with the good tagDestroy the objects in the array
Instantiate your new car
Have fun and drive carefully
Your answer
Follow this Question
Related Questions
How can I switch paths by pressing a button? 1 Answer
Car game Reverse Button 1 Answer
On mouse down switch on / off 2 Answers
Reverse Button problem 0 Answers
Weighing down a heavy switch 2 Answers