I have created two coroutines, one for moving my badGuy game objects right and another for moving them left (please see code below).
IEnumerator moveBadGuyLeft (Transform fromPosition, Vector3 toPosition, float duration, int newIndex) {
while (emptyPos.Contains(badGuyPos[newIndex])) {
emptyPos.Add(badGuyPos[newIndex + 1]);
filledPos.Remove(badGuyPos[newIndex + 1]);
float counter = 0;
Vector3 startPos = fromPosition.position;
while (counter < duration)
{
counter += Time.deltaTime;
fromPosition.position = Vector3.Lerp(startPos, toPosition, counter / duration);
yield return null;
}
emptyPos.Remove(badGuyPos[newIndex]);
filledPos.Add(badGuyPos[newIndex]);
if (newIndex > 0) {
newIndex--;
}
startPos = toPosition;
toPosition = new Vector3 (badGuyPos[newIndex], startPos.y, startPos.z);
int waitInterval = Random.Range(3, 5);
yield return new WaitForSeconds(waitInterval);
}
}
IEnumerator moveBadGuyRight (Transform fromPosition, Vector3 toPosition, float duration, int newIndex) {
while (emptyPos.Contains(badGuyPos[newIndex])) {
emptyPos.Add(badGuyPos[newIndex - 1]);
filledPos.Remove(badGuyPos[newIndex - 1]);
float counter = 0;
Vector3 startPos = fromPosition.position;
while (counter < duration)
{
counter += Time.deltaTime;
fromPosition.position = Vector3.Lerp(startPos, toPosition, counter / duration);
yield return null;
}
emptyPos.Remove(badGuyPos[newIndex]);
filledPos.Add(badGuyPos[newIndex]);
if (newIndex > 0) {
newIndex++;
}
startPos = toPosition;
toPosition = new Vector3 (badGuyPos[newIndex], startPos.y, startPos.z);
int waitInterval = Random.Range(3, 5);
yield return new WaitForSeconds(waitInterval);
}
}
I am trying to move my badGuy objects left till they meet a filled position then move them right till they meet a filled position and so on, toggling between left and right. I know that if my condition
while (emptyPos.Contains(badGuyPos[newIndex]))
is false then I should change from one coroutine to the other or vice versa. How can I implement this changing between coroutines. Please see how I am calling the coroutine in the Start method below:
void Start () {
for (int i = 0; i < badGuys.Count; i++) {
if (badGuys [i].getBlockType () == BadGuySetup.BadGuyType.moving) {
int indexInBadGuyPos = badGuyPos.IndexOf(blocks[i].getBadGuyGameObject().transform.position.x);
Vector3 targetPos = new Vector3(badGuyPos[indexInBadGuyPos - 1], badGuys[i]. getBadGuyGameObject().transform.position.y, 0.0f);
StartCoroutine(moveBadGuyLeft(badGuys [i]. getBadGuyGameObject().transform, targetPos, 1.0f, indexInBadGuyPos - 1));
}
}
}