在前面的项目中,如果我们修改hotfix部分的代码,想要看运行效果,需要每次都编译dll文件然后再执行。在开发过程中会比较繁琐,所以我们可以添加一个选项,使其可以不读取dll,从而调用hotfix的代码来执行项目(也就是忽略ILRuntime功能)。当然这么做之后,我们也需要是不是的编译dll一下,以防一些开发中的ILRuntime的语法错误堆积起来。
首先我们添加一个枚举
public enum AssetLoadMethod
{
Editor = 0,
StreamingAsset,
}
若选择Editor模式,则跳过加载hotfix.dll流程,正常执行我们的Hotfix部分代码。这样就无需每次修改后启动前都需要打一次hotfix.dll文件。
若选择StreamingAsset模式,则加载hotfix.dll,通过ILRuntime.Runtime.Enviorment.AppDomain来执行我们的Hotfix部分代码。
然后在我们的HotfixLaunch中需要添加一个判断,利用Assembly.GetAssembly()来获取所有类型
using Hotfix.Manager;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Tool;
using UnityEngine;
namespace Hotfix
{
public class HotfixLaunch
{
static List<ILifeCycle> managerList = new List<ILifeCycle>();
public static void Start(bool isHotfix)
{
Debug.Log("HotfixLaunch Start");
//获取Hotfix.dll内部定义的类
List<Type> allTypes = new List<Type>();
if (isHotfix)
{
var values = ILRuntimeHelp.appdomain.LoadedTypes.Values.ToList();
foreach (var v in values)
{
allTypes.Add(v.ReflectionType);
}
}
else
{
var assembly = Assembly.GetAssembly(typeof(HotfixLaunch));
if (assembly == null)
{
Debug.LogError("当前dll is null");
return;
}
allTypes = assembly.GetTypes().ToList();
}
//去重
allTypes = allTypes.Distinct().ToList();
//获取hotfix的管理类,并启动
......
}
然后在我们启动的类Launch中添加上面的枚举变量,然后根据变量的值去选择启动的方式即可。
using System;
using System.Reflection;
using Tool;
using UnityEngine;
public class Launch : MonoBehaviour
{
public AssetLoadMethod ILRuntimeCodeLoadMethod;
......
private void Start()
{
if(ILRuntimeCodeLoadMethod == AssetLoadMethod.StreamingAsset)
{
StartCoroutine(ILRuntimeHelp.LoadILRuntime(OnILRuntimeInitialized));
}
else
{
//不直接调用 Hotfix.HotfixLaunch.Start 是防止编译dll的时候找不到 Hotfix部分的Hotfix.HotfixLaunch类而报错
var assembly = Assembly.GetExecutingAssembly();
var type = assembly.GetType("Hotfix.HotfixLaunch");
var method = type.GetMethod("Start", BindingFlags.Public | BindingFlags.Static);
method.Invoke(null, new object[] { false });
}
}
......
}
这样,在我们平时开发的时候选择AssetLoadMethod.Editor模式,就不需要频繁的打dll了。但是一定要定期打dll测试下,防止堆积太多的ILRuntime的语法错误。