Youssef Hossam
Youssef Hossam

Reputation: 103

I want to create a timer/stopwatch on an event

I have a code that works just fine but i think if i keep following the same strategy to do all the same things it's gonna over load on the processor for no reason

I have a variable that represents the time and this variable rests to 0 in every frame that the gameObject has a velocity higher than 0.5f so instead of resetting it every frame i want to start the timer when it's below 0.5f

    if (speed >= 0.5f)
    {
        t = 0;
    }

    t = t + Time.deltaTime;

Upvotes: 2

Views: 117

Answers (1)

Norse
Norse

Reputation: 121

You could use a bool value to save performance.

public static bool isTimerMoving = false;

public void Update()
{
    if (speed < 0.5f)
    {
        t = t + Time.deltaTime;
        isTimerMoving = true;
    }
    else if (isTimerMoving) {
        t = 0;
        isTimerMoving = false;
    }
}

This code resets the timer whenever speed reaches 0.5f. If you only want to pause the timer, you can remove the t = 0 from it.

P.S. using > or < is faster than using <= or >=. Not by very much, but I like keeping things efficient ;)

EDIT: After asking a question, responses indicate that this statement is false, my apologies.

Upvotes: 1

Related Questions