Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Lerp incorect count

Discussion in 'Scripting' started by BigApp7e, Feb 15, 2021.

  1. BigApp7e

    BigApp7e

    Joined:
    Mar 10, 2019
    Posts:
    9
    Hello everyone. I got stuck on a very strange problem. Lerp doesn't count correctly.
    The goal is to count from "startValue" to "endValue" for "lerpDuration" seconds.
    The code is clear enough.
    I tried different combinations with Mathf.Lerp, Vector3.Lerp, Vector2.Lerp but the result is additional one second more each time. Does anyone have idea where this error is coming from?
    Final Result:
    Debug - START 7:57:46:392
    Debug - END 7:57:48:793
    or
    Debug - START 8:19:14:147
    Debug - END 8:19:16:559
    ....?

    void Start()
    {
    timeElapsed = 0;
    lerpDuration = 1;
    startValue = 0;
    endValue = 10;
    lerpCount = startValue;
    Debug.Log("START " + DateTime.Now.ToString("h:mm:ss:fff"));
    allowCount = true;
    }
    void Update()
    {
    if (!allowCount) return;
    if (timeElapsed < lerpDuration)
    {
    lerpCount = Mathf.Lerp(startValue, endValue, timeElapsed / lerpDuration);
    timeElapsed += Time.deltaTime;
    }
    else
    {
    Debug.Log("END " + DateTime.Now.ToString("h:mm:ss:fff"));
    allowCount = false;
    }
    }
     
  2. SparrowGS

    SparrowGS

    Joined:
    Apr 6, 2017
    Posts:
    2,536
  3. BigApp7e

    BigApp7e

    Joined:
    Mar 10, 2019
    Posts:
    9
  4. arfish

    arfish

    Joined:
    Jan 28, 2017
    Posts:
    777
    Hi,
    How about putting some extra Debug.Logs in the code to see how many times the loop is running, and how the values changes in each loop?
     
  5. mopthrow

    mopthrow

    Joined:
    May 8, 2020
    Posts:
    343
    You can edit your post to change it ;)

    Unity runs all Start() functions before it begins to run Update() functions. So you're recording your start time in Start(), Unity is going off doing lots of other work, then later, starting your actual timer in Update() by which time you've got a additional time on your clock.

    Put the start timer code in Update() behind a GetKeyDown(), wait until everything has been initialized, then start the timer. Your results should be regular now. For good measure, set timeElapsed = 0 when you end timing so you can try it without having to restart every time a timer finishes.