- Home /
coroutine for reloading
Ok so this has been driving me mad trying to get the enemy to reload using a coroutine. but it just seems to run as loop inside the coroutine. and uses all the clips at once.
 void Reload()
     {
         StartCoroutine (ReloadDelay());
         
     }
 
 IEnumerator ReloadDelay()
 {
     yield return new WaitForSeconds(5.0f);
     Debug.Log("waiting");
         
         //StartCoroutine (ReloadDelay());
         
         if(Clip > 0)
         {
     
         BulletsLeft = BulletPerClip;
             Clip--;
         
         PlayReloadAudio();
         caseCont = 2;
     }
         
Answer by aldonaletto · Apr 16, 2012 at 12:11 PM
Coroutines are "fire and forget" creatures: you start a coroutine and your code continues almost immediately - the coroutine returns when the first yield is executed, and keeps running in the background each frame. If you call Reload again before the current coroutine has finished, a new one is started. The easiest way to avoid this requires a boolean flag: it's set at the coroutine beginning and reset at the end, and you must only start a new coroutine when the flag is false:
bool reloading = false; // flag indicating "I'm reloading now!"
void Reload(){ // only reload again if the previous coroutine has ended: if (!reloading) StartCoroutine (ReloadDelay()); }
IEnumerator ReloadDelay(){ reloading = true; // signal "I'm reloading..." yield return new WaitForSeconds(5.0f); ... PlayReloadAudio(); caseCont = 2; reloading = false; // reload ended }
Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                