I guess the first question is Why? Why create DLLs?
DLLs can be used to Tidy Up Unity Code, speed up compile time (a bit), makes it easier to redistribute code and a bunch of other Pros (but also Cons), and reduce deployment clutter and you can literally put everything you need – textures, audio, whatever – inside one file.
Okay, so now, How? Unity actually has a pretty good tutorial on How, but it lacks pictures and fails to mention some quirks.
Let’s get started:
- Create a New Solution in MonoDevelop, select C# > Library.
- Specify its Name, Location and Solution Name.
- Reference Unity DLLs, by going to Project > Edit References…
- Select .Net Assembly, and navigate to: /Applications/Unity/Unity.app/Contents/Frameworks/Managed/UnityEngine.dll, and click Add.
- UnityEngine.dll will then be included in the References folder of the Solution.
- Add files by right clicking on the solution and Add > Add Files…
- Before building, make sure that Mono Soft Debugger Support for Unity is disabled. Go to MonoDevelop-Unity > Add-in Manager… Unity > Mono Soft Debugger Support for Unity, and click Disable.
-
Also, make sure Target framework is set to .NET 2.0. Right click on the solution, go to Options > Build > General, and set Target framework.
- Click Build > Build All or Build > Build <Solution Name>.
- The DLL will be saved in the bin/Debug folder of the Solution.
- Copy the DLL file to Assets/Plugins and reference it like any normal script.
There will always be a few Quirks:
- Cyclic dependencies of DLL not allowed
- Can only reference other DLLs
- DLLs cannot be edited in Unity
- DLL with dependencies will log error, if dependency not included in Unity Project
- DLL scripts cannot be in separate folders (Editor scripts need to be in Editor folder -> build separate DLLs for Editor and normal scripts, use Unity Package to sort them into proper folders)
- Change #if UNITY_IPHONE script to if(Application.platform == RuntimePlatform.IPhonePlayer) and change #if UNITY_ANDROID script to if(Application.platform == RuntimePlatform.Android)
- Editor Scripts not working properly -> needs to create a proxy script to bind to Unity (http://forum.unity3d.com/threads/editor-script-dll-and-regular-script-dll-not-adding-custominspector-scripts.107720/)
- DLL with reference to AndroidJavaObject fails to build for iOS
Some quirks which I can’t seem to resolve and I’m hoping someone can help me:
Hi, Why is step 7 necessary?
If you’re creating a Mac library, you have either the option of creating a dylib, which includes only the compiled binary for the library, or creating a framework, which includes the compiled binary as well as headers and other bundle resources used by the library, in a single package. Frameworks are the preferred method of library distribution for the Mac.
If you’re creating an iOS library, iOS doesn’t support dynamic libraries of any kind (no dylibs or frameworks) so you’re stuck with creating static libraries to distribute your code.