0
\$\begingroup\$

I need to create Coroutine that moves from 0 to "maxAmount" over "duration".

Can someone please assist me with the proper way to create this loop?

Here is my attempt at it:

var t = 0
 
While(currentAmount < maxAmount)
{
          currentAmount = Mathf.Lerp(minAmount, maxAmount, t/5f);
          t += .05f * Time.deltaTime;
          yield return null;
}

This moves the amount from 0 to MaxAmount, however, it doesn't seem to take the correct amount of time. (in this case 5 seconds)

\$\endgroup\$
0

1 Answer 1

0
\$\begingroup\$

Managed to figure it out.

What I did was:

float t = 0;

while (currentAmount < maxAmount)
                {
                    currentAmount = Mathf.Lerp(minAmount, maxAmount, t);
                    t += Time.deltaTime/5f;
                    yield return null;
                }

Hopefully this helps someone in the future!

\$\endgroup\$
2
  • \$\begingroup\$ It would be more conventional to put the t increment before the Lerp - otherwise this loop does nothing the first frame. \$\endgroup\$
    – DMGregory
    Jan 3, 2023 at 14:50
  • \$\begingroup\$ Completely missed this! I'll go fix it now. Thanks a a ton, Douglas! \$\endgroup\$ Jan 4, 2023 at 21:17

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .