本文转自:http://blog.csdn.net/lyh916/article/details/44174747,有个人多处修改,请点击链接查看原文,尊重楼主版权。
参考链接:
http://liweizhaolili.blog.163.com/blog/static/1623074420144313825921/
http://blog.csdn.net/janeky/article/details/25923151
Unity与dll不得不说
1.VS编辑器创建C#类的Dll
(这里是VS2017,选择.Net框架的类库,不要选择其他的,之前踩过坑,没有设置dll目标.Net平台的地方)
a.
b.编写代码:(刚进入会默认是Class1这样的,可在右侧解决方案下脚本名上点击修改类名)
using System;
using System.Collections.Generic;
using System.Text;
public class CSharpDll
{
public static int Add(int a, int b)
{
return a + b;
}
}
c.设置属性
右击右侧解决方案下项目,点击属性,默认应用程序切页里设置目标框架为.Net Framework3.5或以下(Unity才支持;输出类型为类库)
然后右击右侧项目,选择生成,生成成功后在右击同样地方打开项目所在文件夹,进入bin/Debug下找到dll。
然后把Dll赋值到Unity项目Assets文件夹下,一般放到Plugins文件夹下,然后再代码中就可以调用了。(Dll的代码有命名空间的需要先引入命名空间)
d.调用
using UnityEngine;
using System.Collections;
public class TestDll : MonoBehaviour {
void Start ()
{
print(CSharpDll.Add(1, 2));
}
}
2.调用dll文件中的MonoBehaviour类
因为MonoBehaviour是Unity的东西,所以在VS里使用它的方法,需要引入Unity的dll。(在Unity里当然不用你引入Unity的dll啦,但是引入命名空间是都要的)
步骤和前面的一样,只是写了using UnityEngine的时候会代码提示错误,所以需要引用UnityEnghine的dll:
右击右侧解决方案下项目,添加引用,在Unity安装目录\Editor\Data\Managed下找到UnityEngine.dll直接添加(脚本中使用的命名空间来自哪些dll,就引用哪些dll)
代码:
using UnityEngine;
using System.Collections;
public class MonoDll : MonoBehaviour {
void Start()
{
print("Start");
}
void Update()
{
print("Update");
}
public void PrintInfo()
{
print("Hello");
}
}
后面步骤还是一样,生成,拿到Unity中,使用:
using UnityEngine;
using System.Collections;
public class TestMonoDll : MonoBehaviour {
void Start ()
{
MonoDll m = gameObject.AddComponent<MonoDll>();
m.PrintInfo();
}
}
调用成功。
3.反射获取dll中属性和方法
将导入的.dll文件改后缀名为.bytes
可以打包上面文件然后AB加载,打包和加载可以参考:http://blog.csdn.net/lyh916/article/details/46289407
这里这个不是重点,我们直接public一个TextAsset变量,然后把bytes文件拖进去:
using UnityEngine;
using System.Collections;
using System.Reflection;
using System;
public class TestDll : MonoBehaviour {
public TextAsset dllAsset1;
public TextAsset dllAsset2;
void Start()
{
Assembly assembly = Assembly.Load(dllAsset.bytes);
Type t = assembly.GetType("CSharpDll"); //有命名空间时要注意
MethodInfo method = t.GetMethod("Add");
System.Object[] p = new System.Object[] { 1, 2 };
print(method.Invoke(t,p));
Assembly assembly2 = Assembly.Load(asset2.bytes);
Type t2 = assembly2.GetType("MonoDll");
gameObject.AddComponent(t2);
}
}
反射获取调用成功。
4.dll反编译
使用工具:Reflector 下载地址:http://pan.baidu.com/s/1kTJDyyb
5.dll混淆:
http://liweizhaolili.blog.163.com/blog/static/1623074420145110502776/
6.dll热更新:(通过反射)
http://www.cnblogs.com/plateFace/p/4790437.html