- Home /
Invoke repeating and StartCoroutine
I'm building a 2d shooter and I want to have a boss which every 5 seconds shoots 3 bullets at the player with 0.5 seconds delay between them , so I would have something like this:
Boss shoots --0.5 seconds-- Boss shoots --0.5 seconds-- Boss shoots --5 SECONDS-- Boss shoots --0.5 seconds-- Boss shoots --0.5 seconds-- Boss shoots --5 SECONDS
Now what I tried was this:
void Start () {InvokeRepeating("trigger",0f,5f);}
IEnumerator trigger(){
yield return StartCoroutine("ripi_fire");
}
IEnumerator multi_fire(){
counter = 3;
while(counter > 0 ){
fire ();
yield return new WaitForSeconds(0.5f);
counter-- ;
}
}
void fire(){
Instantiate(enemy_bullet,this.transform.position, Quaternion.LookRotation(target.transform.position- this.transform.position));
}
But when I try that unity crashes. I read somewhere else that you cannot use Startcoroutine with Invoke. Is it the same with InvokeRepeating? If so, how are you supposes to generate an event like that?
Yield return new WaitForSeconds is the best way to add delay between 2 events and InvokeRepeating is the best way to repeat an event after every X seconds.
Any suggestions?
Answer by coastwise · Dec 03, 2012 at 02:52 AM
Why not roll the whole functionality into a single coroutine like so:
void Start () {
StartCoroutine("FireThriceAndWait");
}
IEnumerator FireThriceAndWait () {
while (true) {
fire();
yield return new WaitForSeconds(0.5f);
fire();
yield return new WaitForSeconds(0.5f);
fire();
yield return new WaitForSeconds(5f);
}
}
void fire(){
Instantiate(enemy_bullet,this.transform.position, Quaternion.LookRotation(target.transform.position- this.transform.position));
}
Is it a good idea to have a while loop in a Coroutine. I mean in terms of performance?
a while loop will not affect a performance, it depends on what it is inside the while loop, but it will basically behave the same as an update event, if you have any specific situation or code i can try and help you
For better performance create 2 variables:
private WaitForSeconds delay05 = new WaitForSeconds(0.5f);
private WaitForSeconds delay5 = new WaitForSeconds(5f);
Then, use them like this:
IEnumerator FireThriceAndWait () {
while (true) {
fire();
yield return delay05;
fire();
yield return delay05;
fire();
yield return delay5;
}
}
This way you only create WaitForSecond Variables 3 times. The way you are doing it always creates new variables.
Your answer
Follow this Question
Related Questions
Shooting Projectiles With controlling attackSpeed 0 Answers
What is the best between StartCoroutine or InvokeRepeating. 5 Answers
Custom fixed update cycle? 6 Answers
InvokeRepeating not executing - recently updated unity 1 Answer
If you disable a gameobject, does an InvokeRepeating loop end or pause? 3 Answers