enemy respawn after amount of time

Hi,

i'm using this script to respawn 5 cubes after 5 secs but i was wondering if there is a better way to do this :

var enemyPrefab : Transform;

function Update ()
{
    if(GameObject.Find("enemyPrefab(Clone)") == false)
    {
        Invoke("reSpawnEnemy", 5);
    }
    else
    {
        CancelInvoke();
    }
}

function reSpawnEnemy()
{
    var position1 = Vector3(Random.Range(-10, 10), 0, Random.Range(-10, 10));
    var enemy1 = Instantiate(enemyPrefab, position1, Quaternion.identity);

    var position2 = Vector3(Random.Range(-10, 10), 0, Random.Range(-10, 10));
    var enemy2 = Instantiate(enemyPrefab, position2, Quaternion.identity);

    var position3 = Vector3(Random.Range(-10, 10), 0, Random.Range(-10, 10));
    var enemy3 = Instantiate(enemyPrefab, position3, Quaternion.identity);

    var position4 = Vector3(Random.Range(-10, 10), 0, Random.Range(-10, 10));
    var enemy4 = Instantiate(enemyPrefab, position4, Quaternion.identity);

    var position5 = Vector3(Random.Range(-10, 10), 0, Random.Range(-10, 10));
    var enemy5 = Instantiate(enemyPrefab, position5, Quaternion.identity);
}

Thanks.

A loop is probably more flexible and better to read as it is shorter, but other than that your code looks fine:

var enemyPrefab : Transform;

function Update ()
{
    if(GameObject.Find("enemyPrefab(Clone)") == false)
    {
        Invoke("respawnEnemy", 5);
    }else
    {
        CancelInvoke();
    }
}

function respawnEnemy()
{
    var position : Vector3;
    for(var i : int = 0; i < 5; i++)
    {
        position = Vector3(Random.Range(-10, 10), 0, Random.Range(-10, 10));
        Instantiate(enemyPrefab, position, Quaternion.identity);
    }
}

You don't want to be doing `GameObject.Find` every frame, it's slow.

Just put a script on your enemy that tells something else that it needs to respawn the enemy in 5 seconds.

So something like this (this might not be exact syntax) on whatever class you're currently using, that your enemy calls when it dies. You might be able to hook into your enemy's `OnDisable` if he doesn't destroy himself.

function respawnEnemyWithDelay( var delay : float )
{
    yield return WaitForSeconds( float );
    // rest of respawn code
}