- Home /
Im trying to make an Timer within a for loop, cant figure it out.
Hello,
I am trying to make a timer inside a for loop. What i want to get out of it, is that every second, it instantiates an enemy, than wait a second, than instantiate, than wait a second, etc. etc.
But i can't figure out where and how to put the timer inside, Could you please be so kind to give me an example.
can someone help me, this is my code :
void SpawnEnemy() {
getwave = GameObject.Find ("HUDObject").GetComponent<HUDScript>();
if(getwave.waveNumber == 1){
for (int i = 0; i < waveOne.Length; i ++){
Instantiate(waveOne[i], new Vector3(transform.position.x, transform.position.y, transform.position.z), transform.rotation);
}
}
Answer by whydoidoit · Mar 16, 2013 at 12:22 PM
You could use either InvokeRepeating or a coroutine.
A loop like that will just hog up the processor time.
So using a coroutine:
IEnumerator SpawnEnemy(float timeBetweenEnemies) {
getwave = GameObject.Find ("HUDObject").GetComponent<HUDScript>();
if(getwave.waveNumber == 1){
for (int i = 0; i < waveOne.Length; i ++){
Instantiate(waveOne[i], transform.position, transform.rotation);
yield return new WaitForSeconds(timeBetweenEnemies);
}
}
Then start it like this:
StartCoroutine(SpawnEnemy(1)); //This way you could make enemies faster on some levels
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Instantiate prefab once help C# 1 Answer
For loop with Vector3.distance does the loop like 20 times per loop 1 Answer
Can't instantiate in loop - crashes unity 1 Answer
instantiate. Code Problem. Help. 1 Answer