2

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;

1 Answers1

1

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.

Norse
  • 121
  • 10
  • no actually after testing this works just fine :) thank you – Youssef Hossam Jun 09 '19 at 06:44
  • 1
    "P.S. using > or < is faster than using <= or >=. Not by very much, but I like keeping things efficient ;)" [citation needed] – yes Jun 09 '19 at 17:11
  • @yes Actually my statement was too broad. It is not true in the case of `int` or any other whole number type, as it is should be optimized at by the compiler changing a `X >= 2` to `X > 1`, but should you be comparing against a `float` or the like, `<=` and `>=` perform both a `==` check and `<` or `>` check. This is because if you were to try to optimize this: `X >= 2` you'd have something like `X > 1.999999999999`, going off into infinity, which shouldn't work. This comes from my own deduction, but I later someone during a video mention this as well. Don't remember which video unfortunately. – Norse Jun 10 '19 at 08:21
  • Also, after searching online I could not find much on this topic other than examples of the whole number optimization (no talk regarding floats and such), but if you find anything that proves otherwise, please do share it. I'm also going to post a question to see if I can get any further insights into the topic. – Norse Jun 10 '19 at 08:24
  • 1
    no need to open a new question -> https://stackoverflow.com/questions/12135518/is-faster-than – yes Jun 10 '19 at 13:17