续上一篇博客,上一篇博客有生成了Test.dll库,下面就利用反射技术把Test.dll库中的脚本代码动态挂载在游戏物体上,在unity场景中新建一个Cube,名为Cube,再新建脚本,名为Test,挂载到Cube上,编辑脚本如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System;
using System.Reflection;
public class Test :MonoBehaviour {
FileStream fs;
Type type;
void Start () {
gameObject.AddComponent(GetType()); //为Cube动态添加脚本
}
public Type GetType() {
fs = new FileStream("Test.dll", FileMode.OpenOrCreate);
byte[]b = new byte[fs.Length];
fs.Read(b, 0, b.Length);
fs.Dispose();
fs.Close();
Assembly assembly = System.Reflection.Assembly.Load(b);
type = assembly.GetType("First." + "Program");
return type;
}
}
运行游戏,你会发现Cube游戏物体上动态挂上了一个名为Program的脚本,并且后台会打印输出"我是dll方法"
动态移除脚本
Destroy(this.gameObject.GetComponent("Program")); //移除脚本
一个很大的坑,当你动态修改Test.dll里面的脚本内容时,再一次调用GetType方法,运行结果还是没修改时的情况,原因我猜想是由于通过文件流读入的是dll库名称没变,有谁知道的还望告知一下!解决方法,动态修改脚本内容时顺便也把编译输出的dll库名称也修改一下(在上一篇博客中修改),这时还得使GetType方法中读入的dll库的名称与修改后的dll库名称一致。