除了簡單地在Unity Editor中Add Component添加C#腳本關聯到具體的GameObject外,如果腳本功能相對獨立或復雜一點,可將腳本封裝成dll文件,unity來調用該dll。
DLL,是Dynamic Link Library的縮寫,Windows平台廣泛存在,廣泛使用,可以使用C#或C++來編寫。
前提:VS安裝有C#或C++開發工具包
1、Unity + C# dll
1 using System; 2 3 namespace CSharpDll 4 { 5 public class Class1 6 { 7 public static string hello(string name) 8 { 9 return name; 10 } 11 } 12 }
成功編譯成dll文件,名字為CsharpDll.dll。
在unity中創建一個Plugins文件夾,所有的外部引用的dll組件必須要放在這個文件下,才能被using。
如果是C#封裝的dll,就用 using的方式引用,如果是C++的dll,就DllImport[""]的方式來添加對dll的引用。
然后我在C#腳本中用這個dll:
1 using System.Collections; 2 using System.Collections.Generic; 3 using UnityEngine; 4 using CSHarpDll; 5 6 public class Test : MonoBehaviour 7 { 8 void OnGUI() 9 { 10 // Load C# dll at runtime 11 if (GUILayout.Button("Test c# dll")) 12 { 13 Debug.Log(Class1.hello("hello world ")); 14 } 15 } 16 }
2、Unity + C++ dll
1 # define _DLLExport __declspec (dllexport) 2 # else 3 # define _DLLExport __declspec (dllimport) 4 #endif 5 6 extern "C" string _DLLExport hello(string name) 7 { 8 return name; 9 }
成功編譯后將生成的CppDll.dll 文件導入unity中的Plugins文件中
此時為C++的dll,就DllImport[""]的方式來添加對dll的引用:
using UnityEngine; using System.Collections; using System.Runtime.InteropServices; //調用c++中dll文件需要引入 public class Test : MonoBehaviour { [DllImport("CppDll")] static extern string hello(string name); // Use this for initialization void Start () { } // Update is called once per frame void OnGUI() { if (GUILayout.Button("Test c++ dll")) { Debug.Log(hello("hello world")); } } }