Home > OS >  Unity -3D: StartCoroutine
Unity -3D: StartCoroutine

Time:04-29

any way i can make this code print "attacking" and than for 2 seconds then print it again and so on. this script just waits for 2 seconds the first time. and then keeps printing it with every frame

public class ZombieAI : MonoBehaviour
{
  
    // Update is called once per frame
    void Update()
    {
            StartCoroutine(time());
        
    }

    IEnumerator time()
    {
        yield return new WaitForSeconds(4);
        Debug.Log("Attacking");

    }
}

CodePudding user response:

You can implement it by doing this

public class ZombieAI : MonoBehaviour
{
  
    // Update is called once per frame
    void Start()
    {
            StartCoroutine(time());
        
    }

    IEnumerator time()
    {
        Debug.Log("Attacking");
        yield return new WaitForSeconds(2);
        StartCoroutine(time());

    }
}

You have to start the coroutine from inside the coroutine. However, if you want to implement this WITHOUT coroutines, do this:

public class ZombieAI : MonoBehaviour
{
    float timer = 0;
    public float attackTimer = 2;
    
    // Update is called once per frame
    void Update()
    {
        timer  = Time.deltaTime;
        if (timer >= attackTimer)
        {
            Debug.Log("Attacking!");
            timer = 0;
        }
        
    }
}

Coroutines can cause headaches, but use whichever one you want :)

CodePudding user response:

Firstly, do not put StartCoroutine() in Update(). That will begin a new coroutine every frame.

Apart from that, you just need to put the action inside a loop, e.g. a for loop. If you want it to keep looping indefinitely until you manually stop the coroutine, you can use:

public class ZombieAI : MonoBehaviour
{
    void Start() // Or anywhere that will only be called once when you want to start the coroutine)
    {
        StartCoroutine(time());
    }

    IEnumerator time()
    {
        while( true ) {
            yield return new WaitForSeconds(2);
            Debug.Log("Attacking");
        }
    }
}
  • Related