Hello,how to run a code for one time only in Update?
like I want to increment health by only one when time is 30 seconds,i ve put another variable or boolean with that,but it didnt work as well,it increments by 20 or 30,any solution?Thanks in Advance
class Example ( )
{ void Update()
{
delaytime+=.2f;
if (DateTime.Now.Seconds==30 && delaytime>3) { delaytime = 0;health++;}
}
It increments by a bunch at a time because seconds == 30 for many frames across the entire second.
Easiest way to do it:
private float lastHealthIncreaseAtTime = -999f;
public float healthIncreaseInterval = 30f;
void Update() {
if (Time.time > lastHealthIncreaseAtTime + healthIncreaseInterval) {
lastHealthIncreaseAtTime = Time.time;
health++;
}
}
Using DateTime is usually only the right way to handle time if you explicitly want to work with time while the game isn’t actively running. Otherwise, use Unity’s Time class.
1 Like
private float timeNextIncrement;
private float incrementDelay = 30f;
private int health = 1;
void Start()
{
timeNextIncrement = Time.time + incrementDelay;
}
void Update()
{
if (Time.time >= timeNextIncrement)
{
health++;
timeNextIncrement += incrementDelay;
}
}