how to: continue invoking when the first object is destroyed

Hello

i am trying to make a game that spawn monsters (using C#)

and this what i want:
1-invoke monster
2-check if the monster is dead
2a-if dead continue invoking
2b-if not dead stop invoking

i mean by “dead” gameobject is destroyed

did some codes but didnt work :frowning:

i am using prefab to summon mobs and i tried the (if monster==null) but it doesnt work

can anyone help me please?

You don’t need invoke, you need a coroutine. Simply keep a reference to the last clone and check if it has been destroyed.

public GameObject monsterPrefab;

IEnumerator Spawn (){
    GameObject clone;
    while (true){
        while (clone){
            yield return null;
        }
        clone = (GameObject)Instantiate(monsterPrefab);
    }
}

If you don’t want to do it with coroutines and you don’t care that the new enemy could appear after some time you can do it with InvokeRepeating:

public GameObject monsterPrefab;
public float respawnCheckTime = 5.0f;
private GameObject clone;

void Start()
{
    ...
    InvokeRepeating("RespawnEnemy", 0, respawnCheckTime);
}

void RespawnEnemy()
{
    if (clone == null)
    {
        clone = Instantiate(monsterPrefab) as GameObject;
    }
}

This will check every respawnCheckTime if the last enemy spawned is alive, if not it will isntantiate a new one. Pretty much what @BoredMormon code does but with InvokeRepeating instead of coroutines.