- Home /
Question by
mmaalex22112 · May 05, 2018 at 12:23 AM ·
c#coroutinelerpmove an objecttranform.position
Help using Lerp inside of a coroutine.
Hello all,
Trying to move a gameobject using lerp. The result I'm getting is that the object moves instantly to the required position rather than over time.
IEnumerator MoveToSpot()
{
Gotoposition = new Vector3(transform.position.x, transform.position.y + 5, transform.position.z);
float elapsedTime = 0;
float waitTime = 3f;
currentPos = transform.position;
while (elapsedTime < waitTime)
{
transform.position = Vector3.Lerp(currentPos, Gotoposition, (elapsedTime / waitTime));
elapsedTime += Time.deltaTime;
}
return null;
}
Would really appreciate the help! <3
Comment
Best Answer
Answer by TreyH · May 05, 2018 at 01:46 AM
You need to yield within that While loop:
while (elapsedTime < waitTime)
{
transform.position = Vector3.Lerp(currentPos, Gotoposition, (elapsedTime / waitTime));
elapsedTime += Time.deltaTime;
// Yield here
yield return null;
}
// Make sure we got there
transform.position = Gotoposition;
yield return null;
while (elapsedTime < waitTime)
{
transform.position = Vector3.Lerp(currentPos, Gotoposition, (elapsedTime / waitTime));
elapsedTime += Time.deltaTime;
return null;
}
This gives an error on the function, that not all code paths return a value. What should I return outside of the while?
$$anonymous$$ake that a yield return null;
while (elapsedTime < waitTime)
{
transform.position = Vector3.Lerp(currentPos, Gotoposition, (elapsedTime / waitTime));
elapsedTime += Time.deltaTime;
yield return null;
}
@JedBeryll ty, typing between games, forgot the most important part