Search Unity

How do i make this repeat?

Discussion in 'Getting Started' started by frogfrogfrogfrogfrog, Mar 2, 2019.

  1. frogfrogfrogfrogfrog

    frogfrogfrogfrogfrog

    Joined:
    Nov 19, 2018
    Posts:
    7
    public IEnumerator Onoff ()
    {
    gameObject.SetActive(true);
    yield return new WaitForSeconds(3);
    gameObject.SetActive(false);
    yield return new WaitForSeconds(3);
    gameObject.SetActive(true);

    }
     
  2. Ryiah

    Ryiah

    Joined:
    Oct 11, 2012
    Posts:
    21,203
    While loop. It's fine to use "infinite" loops inside coroutines as long as you yield at some point.

    Code (csharp):
    1. public IEnumerator Onoff ()
    2. {
    3.     while (true)
    4.     {
    5.         gameObject.SetActive(true);
    6.         yield return new WaitForSeconds(3);
    7.         gameObject.SetActive(false);
    8.         yield return new WaitForSeconds(3);
    9.     }
    10. }
     
  3. frogfrogfrogfrogfrog

    frogfrogfrogfrogfrog

    Joined:
    Nov 19, 2018
    Posts:
    7
  4. frogfrogfrogfrogfrog

    frogfrogfrogfrogfrog

    Joined:
    Nov 19, 2018
    Posts:
    7
    i did StartCoroutine(Onoff()); but it only did it once
     
  5. Ryiah

    Ryiah

    Joined:
    Oct 11, 2012
    Posts:
    21,203
    Ah, I knew I was forgetting something. I forgot to mention that when you disable a game object (eg through SetActive) it will turn off any coroutines running in scripts for that object.