在前面的項目中,如果我們修改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的語法錯誤。