- Home /
Replace gameobject with another
Hi, in my scene i have a car, when its hit by a bullet, the car instantiates a explosion, but then i want to "disappear" the original car, and appear a destroyed car i have in my prefabs, i have no idea where to start, thanks!
You can instantiate the destroyed car with this:
Instantiate(destroyedCarPrefab, originalcar.transform.position, originalcar.transform.rotation);
and destroy the original one like this:
Destroy(originalcar);
The originalcar is a Gameobject variable filled with the original car gameobject. The destroyedCarPrefab is a Prefab or Gameobject variable filled with the prefab of the destroyed car.
You can instantiate a prefab using Instantiate(prefab, position, rotation). You can destroy a game object using Destroy(gameObject).
In your case, you'd want to instantiate the prefab in the same location and rotation of the old object, and then destroy the old one and the explosion:
GameObject destroyedCarGameObject = (GameObject)Instantiate(destroyedCarPrefab, carGameObject.transform.position, carGameObject.transform.rotation);
Destroy(carGameObject);
Destroy(explosionGameObject);
See the documentation here:
http://docs.unity3d.com/Documentation/ScriptReference/Object.Instantiate.html http://docs.unity3d.com/Documentation/ScriptReference/Object.Destroy.html
Just make sure the car prefab and the destroyed car prefab have the same center (pivot) and are facing the same direction when they're rotations are (0,0,0).
Your answer