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 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:
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;
}
}