AddComponent for MonoBehaviour in DLL plugin does not work..

So I have a DLL with a class ResourceManager implemented as a singleton. The GetInstance() method for the class has the following code..

public static ResourceManager GetInstance()
    Debug.Log("ResourceManager Inst");
    if (cInstance == null) {
        GameObject container = new GameObject("ResourceManager");
        cInstance = container.AddComponent<ResourceManager>();
    return cInstance;

where cInstance is defined as..

static ResourceManager cInstance;

This is all happening inside a DLL which is placed in the Plugins folder of my Unity project. So when I make the following inside a script in my Unity scene,


I get the following error..

"Can't add component because 'ResourceManager' is not derived from Component."

So, is it the case that, this kind of code just will not work because it is in a dll or is there something wrong in the way I have done things here?

NOTE: as of Unity 3.x this is now possible.

unity does not support components in external assemblies. a class library (DLL) is an external assembly and you can not have a component in it.

As the error says, components need to derive from the Component class. For scripts inside unity, that means you have to define your class like this:

public class MyClass : Component
  ...class body...

or, as is more commonly used (and is the default when unity creates a new c# script):

public class MyClass : MonoBehaviour
  ...class body...

This works because MonoBehaviour derives from Behaviour, which itself derives from Component.

Whether or not you can do this in your DLL, I'm not sure. I'm guessing you would have to add the UnityEngine.dll to your project, if it's not added already.

Here people

I found a way to do that... not a clean solution but it works nice!

the laboratory blog