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!