Deniz Tuncer Tepe
Deniz Tuncer Tepe

Reputation: 9

I tried to write a reload script but my logic wasn't good enough

IEnumerator Reload(float reloadSpeed)
{
    canShoot = false;
    yield return new WaitForSeconds(reloadSpeed);
    if(totalAmmo >= magazineCapacity)
    {
        totalAmmo -= magazineCapacity - currentAmmo;
        currentAmmo += magazineCapacity - currentAmmo;
    }
    else if(totalAmmo <= magazineCapacity && (totalAmmo -= magazineCapacity - (magazineCapacity - totalAmmo) - currentAmmo) > 0 )
    {
        totalAmmo -=  magazineCapacity - (magazineCapacity - totalAmmo) - currentAmmo;
        currentAmmo += magazineCapacity - (magazineCapacity - totalAmmo) - currentAmmo; 
        
    }
    else
    {
        if(totalAmmo + currentAmmo <= magazineCapacity)
        {
            currentAmmo += totalAmmo;
            totalAmmo = 0;                  
        }
        else
        {
            int leftAmmo;
            leftAmmo = totalAmmo + currentAmmo - magazineCapacity;
            currentAmmo = totalAmmo - leftAmmo;
            totalAmmo = leftAmmo;
        }
    }
    canShoot = true;
}

So when my ammo that isn't reloaded yet is less than 30 I can't reload and it starts to do random stuff like evening my currentAmmo and totalAmmo or leveling my totalAmmo don't know how to fix it

Upvotes: 0

Views: 55

Answers (1)

JDormer
JDormer

Reputation: 315

Instead of making a case for every possibility when reloading, this should be a more generic solution. Mathf.Clamp will stop you from drawing more ammo from total ammo than you have.

IEnumerator Reload(float reloadSpeed)
{
    canShoot = false;
    yield return new WaitForSeconds(reloadSpeed);

    // No ammo? No reload
    if (totalAmmo > 0)
    {
        //Take out the amount of ammo we need. Clamp the amount so that we cant take more than the total ammo
        int amountToWithdraw = Mathf.Clamp(magazineCapacity - currentAmmo, 0, magazineCapacity); 
        totalAmmo -= amountToWithdraw;
        currentAmmo += amountToWithdraw;
    }

    canShoot = true;
}

Upvotes: 1

Related Questions