- Home /
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 :(
i am using prefab to summon mobs and i tried the (if monster==null) but it doesnt work
can anyone help me please?
Answer by Kiwasi · Sep 21, 2014 at 07:37 PM
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);
}
}
is there any other way?
cause i dont know corutine and enumerator :(
There are other ways. @dmg0600 provided one solution. It can also be done with Update as follows
public GameObject monsterPrefab;
GameObject clone;
void Update () {
if (!clone){
clone = (GameObject)Instantiate(monsterPrefab);
}
}
But coroutines are really worth learning. Its one of Unity's more powerful features.
thank you for your comment
but can u answer these 2 questions please?
1-is clone normal gameobject {monster} or its the object spawning {monster(clone)}
2-the if statment doesnt work cause my gameobject is a prefab and it is always not null
Thank you very much
Clone is not your prefab. Clone should be the actual GameObject in the scene. Hence the clone = Instantiate line.
Note my answer is pseudo code. Its meant to demonstrate a point, you can't copy it literally.
Answer by dmg0600 · Sep 22, 2014 at 02:04 PM
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.
thank you for the comment
but can u answer these 2 questions please?
1-is clone normal gameobject {monster} or its the object spawning {monster(clone)}
2-the if statment doesnt work cause my gameobject is a prefab and it is always not null
Thank you very much
Same answer as @Bored$$anonymous$$ormon I will also edit my answer with a variable for the prefab for future reference.