Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Reload Gun

Discussion in 'Scripting' started by LongformStudios, Nov 1, 2015.

  1. LongformStudios

    LongformStudios

    Joined:
    Nov 27, 2014
    Posts:
    6
    Hello Unity!

    So I've been having some difficulties with making a reload system for a gun for my game. I'm trying to add a delay in order to add some sort of affect.

    Here's my code

    Code (CSharp):
    1.  
    2. Debug.Log(Time.time);
    3.  
    4. if (currentAmmo == 0)
    5.         {
    6.             if (Input.GetKey(KeyCode.R))
    7.             {
    8.                 nextReloadTime = Time.time + reloadTime;
    9.                 reload.Play();
    10.  
    11.                 Debug.Log("Reload @ " + nextReloadTime);
    12.             }
    13.             else if (nextReloadTime >= Time.time)
    14.             {
    15.                 Debug.Log("Reload");
    16.             }
    17.         }
    I have it in the void Update () function.

    Whenever I debug it out I get nextReloadTime output properly with the reloadTime variable added to the current time stamp but it outputs it's reload at the time stamp exactly after it shows when it should reload at. Can somebody tell me why this is?

    Thanks,
    James
     
  2. Stardog

    Stardog

    Joined:
    Jun 28, 2010
    Posts:
    1,887
    Try this:
    Code (CSharp):
    1. public bool canReload;
    2.  
    3. void Update()
    4. {
    5.     if (Input.GetKeyDown(KeyCode.R))
    6.     {
    7.         if (!canReload) return;
    8.  
    9.         reload.Play();
    10.         StartCoroutine(Cooldown(2));
    11.     }
    12. }
    13.  
    14. IEnumerator Cooldown(float timeToWait)
    15. {
    16.     // Cooling down
    17.     canReload = false;
    18.  
    19.     yield return new WaitForSeconds(timeToWait);
    20.  
    21.     // Finished cooldown
    22.     canReload = true;
    23. }
     
  3. LongformStudios

    LongformStudios

    Joined:
    Nov 27, 2014
    Posts:
    6


    Worked perfectly. Thank you!