Reload Gun

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

Debug.Log(Time.time);

if (currentAmmo == 0)
        {
            if (Input.GetKey(KeyCode.R))
            {
                nextReloadTime = Time.time + reloadTime;
                reload.Play();

                Debug.Log("Reload @ " + nextReloadTime);
            }
            else if (nextReloadTime >= Time.time)
            {
                Debug.Log("Reload");
            }
        }

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

Try this:

public bool canReload;

void Update()
{
    if (Input.GetKeyDown(KeyCode.R))
    {
        if (!canReload) return;

        reload.Play();
        StartCoroutine(Cooldown(2));
    }
}

IEnumerator Cooldown(float timeToWait)
{
    // Cooling down
    canReload = false;

    yield return new WaitForSeconds(timeToWait);

    // Finished cooldown
    canReload = true;
}

Worked perfectly. Thank you!