- Home /
How to call a custom object from a C# dll
Problem:
(function, file, and class names changed to protect the innocent)
So I have a C# dll named CSharpDLL
so I do this in my unity C# script.
using CSharpDLL;
// later on
private CSharpDLL.CustomObjectName foo; // note that this works just find and doesn't cause any errors
// later on
(I press foo. and mono recognizes the object and shows me the names of all of its member functions, sweet this must be working)
foo.voidMethod(); // this causes the error
foo = new CSharpDLL.CustomObjectName(); // this causes the error and yes there is a default constructor in the dll class
Both of these create the following error in Unity :
Internal compiler error. See the console log for more information. output was: Unhandled Exception: System.TypeLoadException: Could not load type 'CSharpDLL.CustomObjectName' from assembly 'CSharpDLL, Version=1.1.2.1, Culture=neutral, PublicKeyToken=null'.
Note that my CSharpDLL is in the plugin folder.
Question : How do I create an object that is defined in a C# dll and use it?
Thanks
j/w, are you using the global namespace for your .dll?
Answer by Bunny83 · May 11, 2011 at 09:20 PM
Don't put managed C# dlls into the plugin folder. The plugin folder is for native code dlls. If you compiled a "normal" C# dll, unity will import it like any other asset. Unity will strip away the namespace and import the classes into the global namespace (that happends at least with classes that are derived from MonoBehaviour). I'm not sure if all classes are handled that way. I've done only some tests with dlls and unity.
edit
I've just created a test dll that looks like this:
using System; using System.Collections.Generic; using UnityEngine;
namespace ClassLibrary1 { public class DLLTest { public DLLTest() { Debug.Log("Hello World"); } }
}
And in Unity when i execute this line i get the "Hello World" printed.
ClassLibrary1.DLLTest tmpObj = new ClassLibrary1.DLLTest();
As i said, just place the dll somewhere in your assets. If it contains classes that are derived from MonoBehaviour it will show up in the project view as sub-assets of your dll, so you can drag-drop them onto GameObjects
So does using UnityEngine; need to be in the C# DLL then?
Well i've always add the UnityEngine.dll as assembly. If you do that you can use the whole API there. I'm not sure if you have to, i guess it's not necessary but in the end it won't hurt since you build for Unity ;)
Your answer
Follow this Question
Related Questions
Can I use my own input device? 4 Answers
PropertyDrawer: Enum to select extended class 0 Answers
How to create a custom function out of script (See the answer for more) 1 Answer
Cant link PLUGIN.DLL with PLUGIN-EDITOR.DLL 1 Answer
Unity plugins 0 Answers