Can coroutines be used in external C# dlls?

Hey guys, I’m getting a runtime NullReferenceException in the Web Player when trying to use StartCoroutine() in a class loaded from a dll in my Plugins folder.

It looks like the ability to inherit from MonoBehaviour was added in 3.0 (http://feedback.unity3d.com/forums/15792-unity/suggestions/192299-scripting-ability-to-define-monobehaviour-in-dlls). Has anyone gotten this to work?

I know that in the past, Unity did not allow an external dll to inherit from MonoBehaviour and that a workaround was to just pass a MonoBehaviour reference in to your object. Is that still the way to do it? Am I doing something wrong? Thanks in advance!


Init.cs (attached to a game object)

using UnityEngine;
using CoroutineTest;

public class Init : MonoBehaviour {
	void Awake () {
		MyClass API = new MyClass();
		API.startRoutine();
	}
}

MyClass.cs (inside CoroutineTest.dll)

using System;
using System.Collections;
using UnityEngine;

namespace CoroutineTest
{
	public class MyClass : MonoBehaviour
	{
		public MyClass ()
		{
		}

		public void startRoutine()
		{
			Log.debug("calling routine");
			StartCoroutine(myRoutine());	
		}
		
		private IEnumerator myRoutine()
		{
			Log.debug("routine started");
			yield return new WaitForSeconds(1.0F);
			Log.debug("routine finished");
		}
	}
}

Log output

calling routine

NullReferenceException
  at (wrapper managed-to-native) UnityEngine.MonoBehaviour:StartCoroutine_Auto (System.Collections.IEnumerator)
  at UnityEngine.MonoBehaviour.StartCoroutine (IEnumerator routine) [0x00000] in <filename unknown>:0 

No, it should be ok to use coroutines in dlls as long as you inherit from MonoBehaviour. But you’ve done something else wrong:

MyClass API = new MyClass();

Never ever create a MonoBehaviour with new, that won’t work. MonoBehaviours are Components and can only exist on GameObjects. Use AddComponent to add your behaviour to an GameObject and you should be fine.

public class Init : MonoBehaviour{
    void Awake () {
        MyClass API = gameObject.AddComponent<MyClass>();
        API.startRoutine();
    }
}