Respawn random objects

Hi everyone.
I have an object and I want that when it touches an object it will be destroyed.
I want that a random object respawn.
I have a script but it doesn’t work:
var leben : int = 1;
var coins : GameObject;

function Start() {
    var randomIndex : int = Random.Range(0,coins.length);
    Instantiate(coins[randomIndex],transform.position,Quaternion.identity);
}

function OnCollisionEnter() {
    leben = 0;
}

function Update() {
    var randomIndex : int = Random.Range(0,coins.length);
    if(leben == 0) {
       Destroy(gameObject);
       Instantiate(coins[randomIndex],transform.position,Quaternion.identity);
       leben = 1;
    }
}

Thank you!
Sorry for my bad english, hope you understand me

1 Answer

1

You are destroying the object before instantiating the next one.

function Update() {
    if(leben == 0) {
        var randomIndex : int = Random.Range(0,coins.length);
        Instantiate(coins[randomIndex],transform.position,Quaternion.identity);
        Destroy(gameObject);
    }
}

I see a problem with instantiating a new coin, on collision being called in the new coin, and the process repeating (possibly infinitely while the player object is in the collider range), so you need to rethink how you will instantiate a new coin after time delay. But for now, this should solve your current problem.