How to use Lerp???

In this example I’m trying to change object’s scale over given time using coroutine but with no succes, Lerp is done a way faster than it should, why so?
For example if target scale is 5 and duration is 3,
lerp is complete when lerpTime (counter / time) is ~0.37 istead of 1
What is wrong?
Unity 2019.2.5

    public Vector3 newScale = new Vector3(5, 5, 5);
    public float duration = 3;
    public Vector3 currentScale = Vector3.one;
    public float counter;
    [Range(0, 1)]
    public float lerpTime;

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.S))
            StartCoroutine(Scale(newScale, duration));
    }

    IEnumerator Scale(Vector3 target, float time)
    {
        while (counter < time)
        {
            counter += Time.deltaTime;
            lerpTime = counter / time;

            currentScale = transform.localScale;
            transform.localScale = Vector3.Lerp(transform.localScale, target, lerpTime);

            if (transform.localScale == newScale)
                Debug.Break();

            yield return null;
        }
    }

Vector3.Lerp and Mathf.Lerp work analogously to each other.

They take the third argument (which must go from 0.0f to 1.0f), and return a value equal between the first and the second argument.

I’m having trouble tellling what you’re trying to do exactly, but if you want something to scale up over time range, you want to do something like this:

float TimeRange = 4.5f;  // how long to change over

float time = 0.0f;

while(true)
{
  float fraction = time / TimeRange;

  time += Time.deltaTime;

  // now do your lerp, I'll keep it simple here
  outputVector = Vector3.Lerp( startVector, endVector, fraction);

  // TODO: do what you want with outputVector here

  if (fraction >= 1.0f) break;

  yield return null;
}

EDIT: I had some typos above that I cleared up;

The reason I structure it that way is to ensure the final reading is equal to endVector by ensuring the time doesn’t end at something like 4.4995f or something.

You may of course feed the transform.localScale value in, but keep in mind you are changing it every time, so it’s hard for me to reason about what that will do. You probably want to make a copy of it BEFORE the loop, and tween from it to the final scale, but I’m not sure what you’re doing exactly.

1 Like

you lerp from current to target; if you want it to take exactly duration time, you need lerp from start to target
tip: when the coroutine ends, do another assign of scale = target, since the lerp might over/undershoot by some tiny float value

1 Like