Sunday, January 20, 2013

Unity Thoughts & StartCoroutine in a non-MonoBehaviour [Unity][C#]

In revisiting Unity recently I was reminded of a few things that I hit in my first experience with Unity.

  1. Do not make every class a MonoBehaviour. Static classes with initializers or Singletons are also perfectly reasonable too! Just ask yourself if the given class needs an update every frame.
  2. GetComponent is not a quick lookup. Try to limit its use. (Script Optimizations)
  3. If you do have non-UI MonoBehaviour objects (and you probably do) useGUILayout should be false. Learn about it.
  4. If you make a class a MonoBehaviour solely to be capable of running Coroutines consider this alternative: Have a centralized MonoBehaviour be responsible for starting Coroutines in your non-MonoBehaviours.
Coroutines can be used in non-MonoBehaviour objects if you have a central MonoBehaviour object that has a method for starting Coroutines with the desired delegate as a parameter. This MonoBehaviour should be an instance that any object can easily access to run Coroutines. The code below would be in the MonoBehaviour and StartCoroutineDelegate would be called from the non-MonoBehaviour object.

public delegate IEnumerator CoroutineMethod();
   

IEnumerator RunCoroutine(
CoroutineMethod coroutineMethod)
{
    return
coroutineMethod();
}


public void StartCoroutineDelegate(CoroutineMethod coroutineMethod)
{
    StartCoroutine("
RunCoroutine", coroutineMethod);
}



Be sure to read about StartCoroutine and StopCoroutine to learn more!

4 comments:

  1. sweet little post, didnt know about the useguilayout, they should really default that to false (how many objects really have gui on them)

    ReplyDelete
  2. I have a suggestion for an improvement, StartCoroutineDelegate should return Coroutine instead of void, this allows you to yield return when calling it, good for chaining.

    public Coroutine startCoroutine(CoroutineMethod coroutineMethod){
    return StartCoroutine("executeCoroutine",coroutineMethod);
    }

    ReplyDelete
  3. Thanks for the above. It seems to be exactly what I need. It's just that I'm a noob to Unity and C#, so I have no idea how to declare the coroutinemethod that gets passed into these functions. Any hints?

    ReplyDelete