1、创建C#类库,并添加对UnityEngine、UnityEngine.UI的引用。
类库结构:
类库逻辑很简单,代码如下:
1 using System; 2 using UnityEngine; 3 using UnityEngine.UI; 4 5 namespace CustomDLL 6 { 7 public class CustomClass 8 { 9 10 } 11 12 public class CustomDLLClass : MonoBehaviour 13 { 14 public Text Text_Res; 15 private int num = 0; 16 17 void Update() 18 { 19 if (Input.GetKeyDown(KeyCode.A)) 20 { 21 ++num; 22 Text_Res.text = num.ToString(); 23 } 24 } 25 } 26 }
生成dll,然后将dll拷贝到unity工程的StreamingAssets目录下:
在unity中添加测试代码:
1 using System; 2 using System.Collections; 3 using System.Reflection; 4 using UnityEngine; 5 using UnityEngine.UI; 6 7 public class Test : MonoBehaviour 8 { 9 [SerializeField] 10 Text Text_ShowNum; 11 12 string url; 13 14 IEnumerator Start() 15 { 16 url = Application.streamingAssetsPath + "/CustonDLL.dll"; 17 WWW www = new WWW(url); 18 if (!www.isDone) 19 yield return null; 20 21 Debug.Log("执行完毕,现在测试如何加载dll"); 22 Debug.Log("unity创建的默认程序域 : " + AppDomain.CurrentDomain); 23 //在unity创建的默认程序域上加载dll 24 Assembly assemble = Assembly.Load(www.bytes); 25 var types = assemble.GetTypes(); 26 foreach (var item in types) 27 { 28 //显示类所在的命名空间和类名 29 Debug.Log("namespace = " + item.Namespace + " class =" + item.Name); 30 if (item.IsSubclassOf(typeof(MonoBehaviour))) //判断类是否继承自MonoBehaviour 31 { 32 Debug.Log(string.Format("类{0}派生自 MonoBehaviour", item.Name)); 33 //添加组件到当前对象 34 Component com = gameObject.AddComponent(item); 35 FieldInfo info = com.GetType().GetField("Text_Res"); 36 if (null != info) 37 { 38 Debug.Log("成功获取字段"); 39 info.SetValue(com, Text_ShowNum); 40 } 41 else 42 { 43 Debug.LogError("获取字段失败"); 44 } 45 } 46 else 47 { 48 Debug.LogError(string.Format("类{0}并非派生自 MonoBehaviour", item.Name)); 49 } 50 } 51 } 52 }
注意理解34、35行。
添加Text进行测试:
点击A,会发现Text显示的内容会不断增加: