Call Coroutine step after step in foreach loop
I have a list (path) with GameObjects. The current GameObject (with the script attached) should move from one position of the GameObjects in the path to the next stepwise. My current code makes it move to the last position of the path immediately. I already tried with WaitForSeconds
at the end of the Coroutine but as they are all started at once, it has no effect.
What can I do to get the step-after-step effect?
Here my code so far:
public List<GameObject> path;
private Vector3 start;
private Vector3 target;
private float lungeSpeed = .8f;
private float lungeDistance = 5;
private IEnumerator coroutine;
public void StartPath() {
foreach (GameObject field in path) {
start = transform.position;
target = new Vector3(field.transform.position.x + lungeDistance, field.transform.position.y, field.transform.position.z);
coroutine = MoveObject(start, target, lungeSpeed);
StartCoroutine(coroutine);
}
}
IEnumerator MoveObject(Vector3 start, Vector3 target, float speed)
{
float t = 0.0f;
float rate = 1.0f / speed;
while (t < 1.0)
{
t += Time.deltaTime * rate;
transform.position = Vector3.Lerp(start, target, t);
yield return null;
}
yield return new WaitForSeconds(1);
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612181501im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Could not load source 'Coroutines.cs': No source available. 1 Answer
Am I using this Coroutine and IEnumerator correctly? 1 Answer
C# coroutine not waiting on waitForSeconds? 2 Answers
c# shooting problem (probably pretty simple) 2 Answers
Trying to make my code pause using coroutines, what am i doing wrong? 2 Answers