Darin Hinze
Darin Hinze

Reputation: 1

Destroying GameObject and Instantiating a Different GameObject

I have the code for destroying a Cube GameObject when it collides with the Terrain. However, Im not sure how I would then after instantiate a New Sphere GameObject in its place after the cube is destroyed.

This is the current code:

{
void OnCollisionEnter(Collision collision)
{
    if (collision.collider.gameObject.tag != "Destroy") 
    {
        Destroy (gameObject);
    }
}

}

Upvotes: 0

Views: 183

Answers (1)

Migko
Migko

Reputation: 175

1) Attach this script to your terrain game object and not the cube.

2) Add a new tag in the editor for cube objects (e.g cube).

3) Create a new sphere prefab instance that you can access through the script containing the OnCollisionEnter() event.

        void OnCollisionEnter(Collision collision)
        {
           if (collision.collider.gameObject.tag == "Cube")
           {
             //store the transform component of the gameobject to be destroyed.
             var transf = collision.gameObject.transform;

             //Destroy the collided gameobject
             DestroyImmediate(gameObject);

             //Instantiate in the position and rotation of the destroyed object.
             Instantiate(sphere, transf.position, transf.rotation);
           }
        }

Upvotes: 1

Related Questions