Wait for 3 seconds without pausing the entire game

I’m making a 2D tank game and ran into a problem coding the reloading part. After the bullet shoots, I wanted the bullet to wait 3 seconds until it is able to shoot again. For this, I made a bool called reload, which is set to true when it shoots and will set to false after 3 seconds. The problem is, when I tried

System.Threading.Thread.Sleep(1000);

the entire game froze for 1 second. I then decided to write

if (reload == true) {
            if (reloadtime > 0){
                reloadtime = reloadtime - 0.005f;
            }
            if (reloadtime < 0 ^ reloadtime == 0) {
                reloadtime = 3;
                reload = false;
            }

but the time it takes is dependent on the framerate. How can I make it wait 3 seconds without pausing the game?

If you want to use Update to set the reload time, be sure to use Time.deltaTime, which is the amount of seconds between the previous and current frame. That will make the time not dependent on framerate.
Here’s a typical way of going about it:

public class Example : MonoBehaviour {
   float reloadTime = 3f; //Three seconds to reload.
   float currentReloadTime = 0f;

   bool isReloading;

   void Update() {
      if(isReloading) {
        currentReloadTime += Time.deltaTime;

         if(currentReloadTime >= reloadTime) {
            isReloading = false;
            currentReloadTime = 0f;
         }
      }
   }
}

An alternative way is to use coroutines, which, in a nutshell, are functions with the capability of pausing execution for a set duration.
Coroutine example for the same thing:

public class Example : MonoBehaviour {
   float reloadTime = 3f; //Three seconds to reload.
   bool isReloading;

   void Update() {
      if(!isReloading) {
         //Do regular actions when not reloading.
      }
   }

   void Reload() {
      if(!isReloading) {
         isReloading = true;
         StartCoroutine(ReloadRoutine());
      }
   }

   //As soon as this coroutine is started, it will pause on the first line for [reloadTime] seconds before continuing
   //on the next line to set [isReloading] back to false.
   IEnumerator ReloadRoutine() {
      yield return new WaitForSeconds(reloadTime);
      isReloading = false;
   }
}
1 Like