Sleep Syntax Unity

I need some help with the syntax for a script. I have tried WaitForSeconds but it only stops the function that it is in. Basically I’m making a gun script. In which I can input how much ammo in is the gun and when I press the fire button it fires and subtracts one bullet from the clip. And the problem I have is that when I reload I can still pull the trigger and it subtracts the clip into negative numbers. This will mess up later when I Instantiate bullets into the scene so I need to fix it right now.

in case its tl;dr, here is the deal. I need to know the syntax of how to stop the entire script after the computer reads one line. In older languages such as qbasic it’s called “sleep”.
here is my script.

 var bulletsinclip : int;
 var bulletsinclipfull : int;
 var time : float = 20.0f;
 var time2 : float = 20;
 function AmmoDeduction () {
 bulletsinclip = bulletsinclip - 1;
 }
  function Reload(time2 : float) {
     transform.Translate(Vector3.forward * Time.deltaTime * 100);
     yield WaitForSeconds(time2);
     transform.Translate(Vector3.back * Time.deltaTime * 100);
      bulletsinclip = bulletsinclipfull;
 }
 
 function Shoot(time : float) {
     transform.Translate(Vector3.forward * Time.deltaTime * 10);
     AmmoDeduction();
     yield WaitForSeconds(time);
     transform.Translate(Vector3.back * Time.deltaTime * 10);
 }
 
 function Update() {
     if (bulletsinclip < 0) {
     Reload (0.7);
     }
     if (Input.GetButtonDown("Fire1")) {
          Shoot(0.1);
     }
     }

I would suggest rolling this all into a single coroutine.

Pseudo code (C#)

void Start (){
    StartCoroutine(Firing());
}

IEnumerator Firing(){
    while (true){
        while (bulletsinclip > 0) {
            if (Input.GetButtonDown("Fire1")) {
                yield return StartCoroutine(Shoot(0.1f));
            } else {
                yield return null;
            }
        }
        yield return StartCoroutine(Reload (0.7f));
    }
}

Two key principles to note

  • You can yield the a coroutine. This will stop execution of the outer coroutine until the inner coroutine is complete.
  • You can use a while loop with a yield statement to create repetitive behaviour. Save your work first, its easy to create an infinite loop here. Unity cannot recover from an infinite loop in your code