I am trying to implement a coroutine that moves an object to a specific point and then comes back to the origin (specified by me) as a coroutine in Unity, but the coroutine is not executed after returning to the origin. What's wrong?
public class LineManager : MonoBehaviour
{
public Vector3 positionToGo = new Vector3(0, -4, 0);
IEnumerator coroutine;
void Start()
{
coroutine = MoveToPosition(transform, positionToGo, 2f);
}
void Update()
{
if(transform.position.y == 4)
{
StartCoroutine(coroutine);
}
}
public IEnumerator MoveToPosition(Transform transform, Vector3 position, float timeToMove)
{
var currentPos = transform.position;
var t = 0f;
while (t < 1 && currentPos.y > position.y)
{
t += Time.deltaTime / timeToMove;
transform.position = Vector3.Lerp(currentPos, position, t);
yield return null;
}
transform.position = new Vector3(0, 4, 0);
StopCoroutine(coroutine);
}
}