Spawning a new prefab after collision detection and destroying the old one.

Hi all. I’m new to unity. Been using it for all of 3 days. Im writing a ‘game’ and it seems to be going quite well.

The game involves collecting ‘objects’.
What I need to know is the best way of going about destroying the first object when touched and spawning a new one.

The script that spawns the first object works fine, and when you touch it, it dissappears.

Just wondering about getting the next object to spawn.

Here are the scripts that im using:

SpawnCollectable.js

#pragma strict

                var prefab : GameObject;

               

                function Start () {

                                var position: Vector3 = Vector3(Random.Range(-10.0, 10.0), 2, Random.Range(-10.0, 10.0));

                                var object = Instantiate(prefab, position, Quaternion.identity);

                                object.transform.parent = transform;

                                print (Random.Range (0,10));

                }

TouchCollectable

 
 

function OnCollisionEnter(col: Collision){

                //Debug.Log(GameObject);

  if (col.gameObject.tag == "PlayerMarble"){

    Destroy(this.gameObject);

    //Spawn a new one here

  }

}

The second script (TouchCollectable) is attached to the prefab.
Would I call the first script again from within this, or is a whole peice of code needed?

Thanks for the help.

Know that code is played in a consecutive order, so on the second script you cannot spawn a prefab AFTER destroying the gameobject that holds the script itself.
What you need to do is spawn the prefab before destroying the gameobject, this although seems noticable - it’s not, in frames they will happen at exactly same time.

I understand that the second script you show is attached to the gameobject that you collect in game, and after it’s destroyed - you want to spawn a prefab. The code would look like this then:

var myCoolPrefab : Transform; //insert your prefab object in here at the inspector

function OnCollisionEnter(col: Collision){
  if (col.gameObject.tag == "PlayerMarble"){
    Instantiate(myCoolPrefab, transform.position, transform.rotation);
    Destroy(this.gameObject);
  }
}

Check out the Instantiate function and spawning prefabs video here.

Thankyou for the help here. I have managed to get the code to almost work the way I want it to. I am trying to get the next item spawn as a child of another object in the scene. I’v had a good trawl through the manual and references, but just can’t get it quite right. If it makes any difference, I am building to android.

I have the latest build here, if it helps to see what I am trying to do: