版本
unity3d: v2020.1
ILRunTime: v2.1.0
VS : v2022
创建工程
1.在unity3d中新建一个脚本,使用vs打开。
2.在VS中点击 文件 > 新建 > 项目。
3.搜索类库
4.创建项目 HotFixProject
添加引用
1.导入Editor\2020.1.01\Editor\Data\Managed\UnityEngine路径里面的所有.dll文件
2.unity工程\Library\ScriptAssemblies下的Assembly-CSharp.dll,UnityEngine.UI.dll
3.设置引用的dll;属性 > 复制本地 > False. 这样生成dll时就不会把引用的dll导出到本地了
设置导出dll路径
点击属性 > 生成 > 输出路径
创建脚本
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
namespace HotFix_Project
{
public class Class1
{
public void Test()
{
UnityEngine.Debug.Log("Hello word");
}
}
}
生成解决方案
测试
1.在Unity项目中新建脚本Dome.cs 挂在到组件上
2.写入脚本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using ILRuntime.Runtime.Enviorment;
using System.IO;
using System;
using UnityEngine.Networking;
public class Dome : MonoBehaviour
{
ILRuntime.Runtime.Enviorment.AppDomain appdomain;
System.IO.MemoryStream fs;
System.IO.MemoryStream p;
// Start is called before the first frame update
void Start()
{
Debug.Log("Start");
StartCoroutine(LoadHotFixAssembly());
}
IEnumerator LoadHotFixAssembly()
{
appdomain = new ILRuntime.Runtime.Enviorment.AppDomain();
string path = "file://" + Application.streamingAssetsPath + "/HotFix_Project.dll";//***注意热更新文件的路径
string path2 = "file:///" + Application.streamingAssetsPath + "/HotFix_Project.pdb";//***注意热更新文件的路径
Debug.Log("path = " + path);
UnityWebRequest www = UnityWebRequest.Get(path);
www.SendWebRequest();
while (!www.isDone)//是否读取完数据
{
yield return null;
}
byte[] dll = www.downloadHandler.data;
fs = new MemoryStream(dll);
UnityWebRequest www2 = UnityWebRequest.Get(path2);
www2.SendWebRequest();
while (!www2.isDone)//是否读取完数据
{
yield return null;
}
byte[] pdb = www2.downloadHandler.data;
p = new MemoryStream(pdb);
try
{
appdomain.LoadAssembly(fs, p, new ILRuntime.Mono.Cecil.Pdb.PdbReaderProvider());
}
catch
{
Debug.LogError("加载热更DLL失败,请确保已经通过VS打开Assets/Samples/ILRuntime/1.6/Demo/HotFix_Project/HotFix_Project.sln编译过热更DLL");
}
OnHotFixLoaded();
}
void OnHotFixLoaded()
{
object obj = appdomain.Instantiate("HotFix_Project.Class1");//***注意,热更新项目名称.类名
appdomain.Invoke("HotFix_Project.Class1", "Test", obj);//***注意,热更新项目名称.类名,这里的test为函数名
}
private void OnDestroy()
{
if (fs != null)
fs.Close();
if (p != null)
p.Close();
fs = null;
p = null;
}
}