- Home /
i have a problem with reloading with Time.time 2d game c# Unity 2020.2
Hello, I hope u are doing great, I have trouble with this part of my code
public float cool = 3.1f; public float munition = 3; private float next = 0.0f; void Update { if (Input.GetKeyDown(KeyCode.DownArrow) && munition > 0){ Instantiate(projectil, offlaunch.position,transform.rotation); munition--; } if (munition < 3 && Time.time > next) { next = Time.time + cool; munition++; Debug.Log(munition); } }  I am doing a shoot, munition and automatic reload system and it almost works, the shooting sytem, and the munition system worked perfectly until i put the reload system, the reload activates when i shoot a lot of times and fast so now the munition system is not working how it will be , and when i finally can use the 3 bullets it reloads fine , but i dont know what to do help please 
Answer by Llama_w_2Ls · Apr 12, 2021 at 03:36 PM
Side note: Leave a space between your text and your code so that it isn't formatted like this: void Update() { //.... } but like this:
 void Update()
 {
     //....
 }
Secondly, use a coroutine to wait some time before completing an action. Here's an example of a basic reload script:
 public class WeaponScript : MonoBehaviour
 {
     public float cool = 3.1f;
     public float munition = 3;
 
     public float ReloadSpeed = 0.5f;
 
     void Start()
     {
         StartCoroutine(Reload());
     }
 
     void Update()
     {
         // Shoots
         if (Input.GetKeyDown(KeyCode.DownArrow) && munition > 0)
         {
             Instantiate(projectil, offlaunch.position, transform.rotation);
             munition--;
         }
     }
 
     IEnumerator Reload()
     {
         while (true)
         {
             if (munition == 0)
             {
                 while (!Input.GetKeyDown(KeyCode.DownArrow) || munition < 3)
                 {
                     yield return new WaitForSeconds(ReloadSpeed);
                     munition++;
                 }
             }
             else
             {
                    yield return null;
             }
         }
     }
 }
This waits some time then adds one to your munition, as long as there's no input and your ammo isn't full. @eduardochewaca
-1 for starting a coroutine every frame while munition == 0
Whoops. It's supposed to be in Start. My bad.
Your new implementation of Reload created an endless loop making the game freeze (missing yield return null; before closing the while(true) loop) 
Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                