I have a robot in a topdown game that moves one tile randomly. His movement is stored in a list, because I want the player to have to copy his movements. Each movement is remembered, so that his list of moves gets longer and harder to follow. The problem is that in the foreach loop, all of his movements are applied at once.
Here’s what I mean.
foreach (Vector3 pos in pattern)
{
robot.Translate(pos);
Debug.Log(pos);
}
the patterns are added correctly, for instance the console might say something like:
(1, 0, 0)
(-1, 0, 0)
(0, 1, 0)
but all the movements are applied at the same time, so in this example he looks like he moves one space up instead of right, left, up.
I think I must be not understanding how foreach loops work, but I can’t think of a way to fix this. I hope my problem is clear enough, I’ll be glad to clarify
That certianly seems to be the case. There’s nothing about a for loop that says “stop and wait for some amount of time between iterations.” As with all code, Unity will blaze through it as fast as possible. If you want that kind of behavior, coroutines are a simple way to do it:
// in your other code...
StartCoroutine(ApplyMotionOverTime(pattern));
...
IEnumerator ApplyMotionOverTime(List<Vector3> pattern) {
foreach (Vector3 pos in pattern)
{
robot.Translate(pos);
Debug.Log(pos);
// This tells Unity to actually wait for some time before continuing. It only works inside coroutines.
yield return new WaitForSeconds(1f);
}
}
Thanks! Exactly what I needed. Funnily enough I had a coroutine in the script that called that method. It wasn’t really doing anything before that so I got rid of it and put it here. I should also mention that it didn’t work until I encased the foreach loop within in While(true) loop. It only called once before then