If you add something every frame you just have to multiply the desired “amount per sec” by Time.deltaTime. Of course that only works properly with floating point numbers since integers can only hold whole numbers so you can’t add a fraction.
float someVar = 0;
void Update()
{
someVar += 50 * Time.deltaTime;
}
This will add “50” every second in a continous way. So each frame you add a fraction of the whole number. At about 60fps after the first frame someVar would be “0.833”. The second frame it would be “1.66” and after 60 frames it’s about “50.0”. After 120 frame (2 seconds) it’s “100.0”
If you talk about integer variables you might want to look at InvokeRepeating like @Search said. However keep in mind that would increment the variable only once every second so after a second it jumps from 0 to 50 or whatever you add.
edit
So if you want to add a fix amout only once over a certain amount of time you’re best of with a coroutine. You can create a “framework” which you can pass a delegate to do that:
IEnumerator _RunForTime(float aDuration, System.Action aCallback)
{
float t = 0f;
while(t < aDuration)
{
t += Time.deltaTime;
aCallback();
yield return null;
}
}
public void RunForTime(float aDuration, System.Action aCallback)
{
StartCoroutine(_RunForTime(aDuration, aCallback));
}
Now you can simply call RunForTime like this:
RunForTime(2f,()=>someVar += 100*Time.deltaTime);
Execute that line once and it will add 100 to someVar over the time of 2 seconds. Note that the endresult could vary slighly due to framerate fluctuations.
If you want to get the amount as precise as possible you could do this:
IEnumerator _AddOverTime(float aDuration, float aAmount, System.Action<float> aCallback)
{
float t = 0f;
float step = aAmount / aDuration;
while (t < aAmount)
{
float add = step * Time.deltaTime;
if (add >= aAmount - t)
{
aCallback(aAmount - t);
yield break;
}
aCallback(add);
t += add;
yield return null;
}
}
public void AddOverTime(float aDuration, float aAmount, System.Action<float> aCallback)
{
StartCoroutine(_AddOverTime(aDuration, aAmount, aCallback));
}
And use it like this:
AddOverTime(2f, 500f, (a)=>someVar += a);
So the callback receives the proper amount that should be added. As soon as the internal counter reached the goal it’s terminated.