- Home /
c# enemy's not spawning
Only the first 2 enemy's will spawn but none after that, also if spawnRate is higher the 0 then they don't spawn at all?
using UnityEngine;
using System.Collections;
public class enemySpawn : MonoBehaviour {
public GameObject enemy;
private float timePassed = 0f, spawnRate = 0f, spawnTimer = 0f;
private int numberOfEnemy = 2;
void Start()
{
StartCoroutine(Speed());
StartCoroutine(Spawn());
}
IEnumerator Speed()
{
timePassed += Time.deltaTime;
if(timePassed >= 10.1f) {
timePassed = 0.0f;
numberOfEnemy++;
spawnRate -= 0.5f;
yield return spawnRate;
yield return numberOfEnemy;
yield return timePassed;
}
}
IEnumerator Spawn()
{
spawnTimer += Time.deltaTime;
if(spawnTimer > spawnRate) {
for (int i = 0; i < numberOfEnemy; i++) {
Instantiate(this.enemy);
}
spawnTimer = 0.0f;
yield return spawnTimer;
}
}
}
The conditional in Speed() is not true on the first time you call it and therefore that code will never see the light of materialization. Since I don't see you call it again, looks like numberOfEnemys will always be 2 and the function will ter$$anonymous$$ate thereafter and unless you call these functions again at some point, nothing will change.
Time.deltaTime is the time that has passed since the last frame so I don't think the conditional in Speed() will ever be true. $$anonymous$$aybe you meant Time.time which is the time that has passed since the beginning of the game, but still the first time you call it from the Start function, it won't be true. And the coroutine will effectively end without having done anything. A while statement within the coroutine, will probably better suite your needs
Answer by livevlad · Mar 04, 2014 at 12:19 PM
Try this function :
IEnumerator Spawn()
{
while(true){
return yield new WaitForSeconds (spawnRate);
for (int i = 0; i < numberOfEnemy; i++) {
Instantiate(this.enemy);
}
}
}
WaitForSeconds will, as its name says, wait some seconds. It waits but does not stop the main thread.
Hope it helps !