- Home /
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
Answer by Bunny83 · Oct 14, 2011 at 12:31 AM
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();
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613010108im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Monobehaviours & Editors with Inheritance across DLL boundaries don't load into Unity 2 Answers
Avoid using MonoBehaviour just for StartCoroutine or WWW load 0 Answers
Is there a way to hide a dll MonoBehaviour, or disallow adding it? 1 Answer
StartCoroutine can't be called from a GameObject. Am I late to this party? 2 Answers
Load a DLL only when needed ? 1 Answer