Search Unity

While loop with coroutine not returning

Discussion in 'Scripting' started by Llamabro4, Jun 18, 2019.

  1. Llamabro4

    Llamabro4

    Joined:
    Jun 13, 2018
    Posts:
    13
    So, right now i am trying to create a really simple enemy script where the enemy jumps and spins every two seconds. I am using a true while loop and a coroutine but for some reason the while loop doesnt return to yield again and continues to call the lines below the waitforseconds. I dont know if im crazy because this has never happened to me before but if anyone can point out what im missing than that is much appreciated. Thanks!

    Btw just ignore "_isHopping"

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Enemy : MonoBehaviour
    6. {
    7.     private Rigidbody2D rb;
    8.  
    9.     [SerializeField]
    10.     private bool _isHopping = false;
    11.     [SerializeField]
    12.     private float _jumpForce = 430.0f;
    13.  
    14.     // Start is called before the first frame update
    15.     void Start()
    16.     {
    17.  
    18.     }
    19.  
    20.     // Update is called once per frame
    21.     void Update()
    22.     {
    23.        
    24.     }
    25.  
    26.     private void FixedUpdate()
    27.     {
    28.         rb = gameObject.GetComponent<Rigidbody2D>();
    29.  
    30.         StartCoroutine(EnemyAction());
    31.         //spin when jump
    32.         //on collission with player, die and drop coins
    33.     }
    34.  
    35.     IEnumerator EnemyAction()
    36.     {
    37.         while (true)
    38.         {
    39.             _isHopping = false;
    40.             yield return new WaitForSeconds(2.0f);
    41.             _isHopping = true;
    42.  
    43.             float randX = Random.Range(-300, 300);
    44.             rb.AddForce(Vector3.up * _jumpForce);
    45.             rb.AddForce(Vector3.right * randX);
    46.             rb.MoveRotation(1);
    47.         }
    48.     }
    49. }
    50.  
     
  2. unity_V_0twZiF8yYYXw

    unity_V_0twZiF8yYYXw

    Joined:
    Jun 18, 2019
    Posts:
    3
    I think that's because you're calling the coroutine repeatedly in your FixedUpdate.

    Something like that happened to me.
     
    Joe-Censored and Vryken like this.
  3. WallaceT_MFM

    WallaceT_MFM

    Joined:
    Sep 25, 2017
    Posts:
    394
    Exactly this. You are creating many coroutines in FixedUpdate, one every physics step. Try starting it in Start instead.
     
    Joe-Censored and Vryken like this.
  4. Llamabro4

    Llamabro4

    Joined:
    Jun 13, 2018
    Posts:
    13
    Ahh ok. Thanks so much for the help!