Search Unity

Resolved Coroutine Not Starting (nvm solved it)

Discussion in 'Scripting' started by tabagoo, Nov 18, 2020.

  1. tabagoo

    tabagoo

    Joined:
    Oct 8, 2020
    Posts:
    4
    So I have a script that's supposed to change the material of a box every 3 seconds:

    public class testcolorchange : MonoBehaviour
    {
    public int x;
    [SerializeField] private Material[] material;
    Renderer rend;
    void Start()
    {
    rend = GetComponent<Renderer>();
    rend.enabled = true;
    StartCoroutine(ChangeMat());
    }
    private static System.Random r = new System.Random();
    IEnumerator ChangeMat()
    {
    x = r.Next(0, 3);
    rend.sharedMaterial = material[x];
    yield return new WaitForSeconds(3);
    }
    }

    But the material never changes, what's the error I'm not seeing?
     
  2. eses

    eses

    Joined:
    Feb 26, 2013
    Posts:
    2,637
    Hi @tabagoo

    Please use code tags when posting code...

    Anyway - when your coroutine runs to its end, you'll have restart it again if you want it to run like an endless loop.

    So do
    StartCoroutine(ChangeMat());
    on the last line of your coroutine (for example).
     
  3. Bunny83

    Bunny83

    Joined:
    Oct 18, 2010
    Posts:
    3,993
    Do not recommend this. It's a bad idea to use coroutines that way. If you want the coroutine to loop, just use a loop inside the coroutine. Starting coroutines always allocates memory. Constantly starting new coroutines is a bad idea. Of course sometimes there may be no other way when you actually start it through an event for example. However never start a new coroutine to loop it.
     
    eses likes this.
  4. eses

    eses

    Joined:
    Feb 26, 2013
    Posts:
    2,637
    I'm sure you are right / have to admit I've done that quite often :). But I guess this would be better then? Although that WaitForSeconds could be cached too...

    Code (CSharp):
    1. IEnumerator Loop()
    2. {
    3.     while (true)
    4.     {
    5.         Debug.Log("Doing something...");
    6.         yield return new WaitForSeconds(1);
    7.     }
    8. }
     
    Bunny83 likes this.