# Refilling ammo over time, using one line of deltatime code?

In my game, I would like to make guns player is using would generate their ammo over time. And I would like to make that time of generation to be differ by different guns, based on its reload time(time would take if gun manually reload), and magsize(capacity of magazine, so that we can computer how much would take to reload a single bullet).

for doing it on my own, I think I could been able to make this logic using if, and another timer virable. like this:

``````public void PassiveReload()
{
if (Ammo < gunData.magsize)
{
//Ammo += Time.deltaTime * (gunData.reloadTime / 3);

AmmoRegenTimer += Time.deltaTime;
if (AmmoRegenTimer >= (gunData.reloadTime / gunData.magsize) * 3)
{
Ammo += 1f;
AmmoRegenTimer = 0f;

}

}
else AmmoRegenTimer = 0f;
}
``````

But, if possible, i would like to keep this simple and make same time of regeneration by multiflying or dividing deltaTime, and adding it straight to Ammo variable, just like //comment i left within code.

If `Ammo` is a float, then I think this should be possible. In essence, if you want to complete one full reload every `gunData.reloadTime` seconds, then you need to do 1/reloadTime reloads per second. For example, if the reloadTime is 2 seconds, then you complete 0.5 reloads every second.

``````float reloadsPerSecond = 1 / gunData.reloadTime;
``````

Given this reload rate, we can multiple by a time value to determine how much of a reload was completed in that time interval.

``````float howMuchReloadToDo = Time.deltaTime / gunData.reloadTime;
``````

A full reload consists of adding `gunData.magsize` bullets to the gun, so we can multiply this reload amount by the magsize to get the amount of bullets to add.

``````float bulletsToAdd = gunData.magsize * Time.deltaTime / gunData.reloadTime;
//or just directly:
Ammo += gunData.magsize * Time.deltaTime / gunData.reloadTime;
``````

With the if statement in your original code, `Ammo` will be able to exceed `magsize` by a small amount very briefly. If you want to make sure that `Ammo` never exceeds `magsize`, you will need to clamp it.

``````Ammo = Mathf.Clamp(Ammo + gunData.magsize * Time.deltaTime / gunData.reloadTime , 0, gunData.magsize);
``````

I think this meets the “one line” goal, but it is kind of a mess to read and would probably be better split up over a few lines, but this will avoid obvious if/else trees and timers if that is your goal.

If I’m understanding correctly, I feel like you could handle this reload directly in the Update function using a timer and gun ammo variables.

Or you could call your function every frame with some updated logic. Your base code looks good though, and almost there!

This would be my suggestion:

``````void Update
{
if (Ammo < gunData.magsize)
{
if (AmmoRegenTimer >= (gunData.reloadTime / gunData.magsize) * 3)
{
Ammo += 1f;
AmmoRegenTimer = 0f;

}
else
{
AmmoRegenTimer += Time.deltaTime;
}
}
}
``````