Files
5.24BuYu/Assets/MyGame/Editor/HotDllStreamingAssetsSync.cs
T
2026-10-20 23:36:47 +08:00

79 lines
3.1 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.IO;
using HybridCLR;
using HybridCLR.Commands;
using UnityEditor;
using UnityEditor.Build;
using UnityEditor.Build.Reporting;
using UnityEngine;
/// <summary>
/// 打包前自动把最新编译出的热更 dll 刷进 StreamingAssets/HybridCLR/Hotfix。
///
/// 为什么需要它:
/// HybridCLR 的 CompileDll / GenerateAll 只把热更 dll 编译到
/// Library/HybridCLR/HotUpdateDlls/{平台},**不会**替你放进 StreamingAssets。
/// 而运行时 Launcher 是从 StreamingAssets/HybridCLR/Hotfix/*.dll.bytes 读 dll 的,
/// 所以少了这一步,打出来的包跑的还是上一次的旧热更代码
/// (现象:改了热更代码、也跑过 Generate/All,但打包出来行为没变)。
///
/// 用法:默认每次打包自动执行,无需手动操作。
/// 想临时关掉,把 AutoSyncOnBuild 改成 false 即可;
/// 也可以手动执行菜单 Tools/刷新热更Dll到StreamingAssets。
/// </summary>
public class HotDllStreamingAssetsSync : IPreprocessBuildWithReport
{
/// <summary>打包前是否自动同步热更 dll</summary>
private const bool AutoSyncOnBuild = true;
/// <summary>运行时读取热更 dll 的目录(相对项目根)</summary>
private const string StreamingHotfixDir = "Assets/StreamingAssets/HybridCLR/Hotfix";
public int callbackOrder => 0;
public void OnPreprocessBuild(BuildReport report)
{
if (!AutoSyncOnBuild) return;
Sync(report.summary.platform);
}
[MenuItem("Tools/刷新热更Dll到StreamingAssets")]
public static void SyncActive()
{
Sync(EditorUserBuildSettings.activeBuildTarget);
EditorUtility.DisplayDialog("热更 dll",
"已把最新热更 dll 刷进 StreamingAssets/HybridCLR/Hotfix", "好");
}
/// <summary>按目标平台重新编译热更 dll,再以 .dll.bytes 命名覆盖到 StreamingAssets。</summary>
private static void Sync(BuildTarget target)
{
// 用目标平台重新编译(输出到 Library/HybridCLR/HotUpdateDlls/{target})
CompileDllCommand.CompileDll(target);
string srcDir = SettingsUtil.GetHotUpdateDllsOutputDirByTarget(target);
Directory.CreateDirectory(StreamingHotfixDir);
bool allOk = true;
// 列表直接取 HybridCLRSettings 的配置(形如 "Game.Hotfix.dll"),不再手写死
foreach (var dllFile in SettingsUtil.HotUpdateAssemblyFilesExcludePreserved)
{
string src = Path.Combine(srcDir, dllFile);
if (!File.Exists(src))
{
Debug.LogError($"[HotDll] 找不到热更 dll 编译产物: {src}");
allOk = false;
continue;
}
string dst = Path.Combine(StreamingHotfixDir, dllFile + ".bytes");
File.Copy(src, dst, true);
Debug.Log($"[HotDll] 已同步热更 dll: {src} ==> {dst}");
}
if (!allOk)
throw new BuildFailedException("[HotDll] 热更 dll 同步失败,请先执行 HybridCLR > CompileDll 看报错");
AssetDatabase.Refresh();
}
}