Search Unity

Problem with startcoroutine

Discussion in '2D' started by brainyxs, May 25, 2019.

  1. brainyxs

    brainyxs

    Joined:
    May 25, 2019
    Posts:
    13
    I have a Porblem. I try to recreate the 2D roghlike game. My Enemys and the Player arent moving.
    The Problem is in the Coroutine. The Log1 is Displayed, but Log 2 isnt.
    Code:

    Code (CSharp):
    1. void Update()
    2.     {
    3.         if (playersTurn || enemiesMoving)
    4.             return;
    5.         StartCoroutine(MoveEnemies());
    6.         Debug.Log("Log1");
    7.  
    8.     }
    9. IEnumerator MoveEnemies()
    10.     {
    11.         enemiesMoving = true;
    12.         yield return new WaitForSeconds(turnDelay);
    13.         if (enemies.Count == 0)
    14.         {
    15.             yield return new WaitForSeconds(turnDelay);
    16.         }
    17.  
    18.         for (int i = 0; i < enemies.Count; i++)
    19.         {
    20.             enemies[i].MoveEnemy();
    21.             Debug.Log("2");
    22.             yield return new WaitForSeconds(enemies[i].moveTime);
    23.         }
    24.  
    25.         playersTurn = true;
    26.         enemiesMoving = false;
    27.  
    28.     }
    29.     public void MoveEnemy()
    30.     {
    31.         int xDir = 0;
    32.         int yDir = 0;
    33.  
    34.         if (Mathf.Abs(target.position.x - transform.position.x) < float.Epsilon)
    35.             yDir = target.position.y > transform.position.y ? 1 : -1;
    36.         else
    37.             xDir = target.position.x > transform.position.x ? 1 : -1;
    38.  
    39.         AttemptMove<Player>(xDir, yDir);
    40.     }
    41.  
    42.  
     
  2. Vryken

    Vryken

    Joined:
    Jan 23, 2018
    Posts:
    2,106
    Do not start coroutines every frame; this will just endlessly create/restart them.
     
  3. brainyxs

    brainyxs

    Joined:
    May 25, 2019
    Posts:
    13
    It doesnt start when Enemiesmoving = true. And at the start of the Coroutine, its set to true and at the end to false. Shouldnt this work?