- Home /
How to run code after loop in coroutine
Hello, all. I'm not very familiar with coroutines, but I am trying to use a coroutine with Vector3.Lerp to move an instantiated prefab to a specific position. After it reaches the target position, I want the object to destroy itself. I'm using Unity 2020.2 with MacOS.
private IEnumerator GoToTargetPosition()
{
float tick = 0f;
while (transform.position != targetPosition)
{
tick += Time.deltaTime * 3;
transform.localPosition = Vector3.Lerp(originalPosition, targetPosition, tick);
yield return null;
}
Destroy(this.gameObject);
}
Thanks!
IEnumerator GoToTargetPosition ( Vector3 from , Vector3 to , float duration )
{
float timer = 0;
while( timer < duration )
{
transform.position = Vector3.Lerp( from , to , timer/duration );
timer += Time.deltaTime;
yield return null;
}
}
while (transform.position != targetPosition)
wont work with local position:
transform.localPosition =
replace it with:
transform.position =
Answer by Icni · Mar 06, 2021 at 07:44 PM
Okay, folks. I edited the code to include an if statement at the end of a while (true) loop, and now it seems to work! Hopefully this works for others as well. So far my program hasn't crashed :).
private IEnumerator GoToTargetPosition() { float tick = 0f; while (true) { tick += Time.deltaTime * 3; transform.localPosition = Vector3.Lerp(originalPosition, targetPosition, tick); if (transform.localPosition == targetPosition) { Destroy(this.gameObject); } yield return null; } }