2

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])) { //how to switch to moveBadGuyRight when this condition is false

        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])) { //how to switch to moveBadGuyLeft when this condition is false

        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:

for (int i = 0; i < badGuys.Count; i++) {
        if (badGuys [i].getBlockType () == BadGuySetup.BadGuyType.moving) {
            int indexInBadGuyPos = badGuyPos.IndexOf(badGuys[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));

    }
}

UPDATE

I added the following to the if (newIndex) > 0 condition in moveBadGuyLeft and moveBadGuyRight:

in moveBadGuyLeft:

            if (newIndex  > 0)  {

                    newIndex--;

            if (!emptyPos.Contains(badGuyPos[newIndex])) {
                isMovingLeft = false;
                badGuyDestPos = new Vector3(badGuyPos[newIndex + 2], startPos.y, startPos.z );
                badGuyNewIndex = newIndex + 2;
                break;
            }
        }

in moveBadGuyRight:

if (newIndex  > 0)  {

                    newIndex++;

            if (!emptyPos.Contains(badGuyPos[newIndex])) {
                isMovingLeft = false;
                badGuyDestPos = new Vector3(badGuyPos[newIndex - 2], startPos.y, startPos.z );
                badGuyNewIndex = newIndex - 2;
                break;
            }
        }

Then I created another coroutine which is suppose to change between the two coroutines:

    IEnumerator movingBadGuys(Transform fromPosition, Vector3 toPosition, float duration, int newIndex) {
    if(isMovingLeft){
        yield return StartCoroutine (moveBadGuyLeft(fromPosition, toPosition, duration, newIndex)); 
    }
    else if(!isMovingLeft){
        yield return StartCoroutine (moveBadGuyRight(fromPosition, toPosition, duration, newIndex)); 
    }
}

Finally I updated looping through the badguys and moving them:

for (int i = 0; i < badGuys.Count; i++) {
    if (badGuys [i].getBlockType () == BadGuySetup.BadGuyType.moving) {
        int indexInBadGuyPos = badGuyPos.IndexOf(badGuys[i].getBadGuyGameObject().transform.position.x);
        Vector3 targetPos = new Vector3(badGuyPos[indexInBadGuyPos - 1], badGuys[i]. getBadGuyGameObject().transform.position.y, 0.0f);

        badGuyDestPos = targetPos;
        badGuyMoveDuration = 1.0f;
        badGuyNewIndex = indexInBadGuyPos - 1;
        StartCoroutine(movingBadGuys(badGuys [i]. getBadGuyGameObject().transform, badGuyDestPos, badGuyMoveDuration, badGuyNewIndex));

    }
}

But this is changes are not working. I am testing it with only two badGuys which always start moving left and they only move left once and stop though there are other empty positions for them to continue moving left.

3 Answers 3

0

Unfortunately, I think this is not a good way to use coroutines. A better approach would be to have a single coroutine "moveBadGuy" then have the BadGuy object have a move method, and some internal state variable. For example.

class BadGuy{
   bool moveLeft = false;

   public void move(){
       if(moveLeft){
           //move the guy left 

       }else{
          //move right 

       }   
   }    
}

Then your coroutine can do

 public IEnumerator moveBadGuy(BadGuy guyToMove){

     guyToMove.move();   

 }

Another solution involving a single coroutine would be to have a moveLeft function and a moveRight function. For example,

public IEnumerator moveBadGuy(){

    if(shouldmoveleft){
        moveLeft();
    }else{
        moveRight();
    }
}

public void moveLeft(){
    //logic for moving left
}

public void moveRight(){
    //logic for moving right
}
0

I recommend that you dont depend on while , what you can do is use the ability of courotuines to yield another coroutine like this yield return StartCoroutine(myFunc());

0

I personally wouldn't give the responsibility to the Move[Right|Left] coroutine to stop themselves.

Since coroutines are just iterator blocks you can even abstract further, and let the parent coroutine drive their execution.

Here's an abstract example:

IEnumerator AlternateOnCondition(Func<bool> evaluateCondition,
                                IEnumerator firstAction,
                                IEnumerator secondAction)
{
    while(true)
    {
        if(evaluateCondition())
        {
            if (firstAction.MoveNext())
                yield return firstAction.Current;
        }
        else
        {
            if (firstAction.MoveNext())
                yield return secondAction.Current;
        }
        yield return null;
    }
}

This is just an example of course, but it should give you the idea how coroutine can be nested.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.