將以下代碼放入Editor文件夾,點擊菜單欄的XLua/一鍵生成代碼和熱補丁 即可。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEditor;
using UnityEngine;/// <summary>
/// XLua自動化構建工具
/// </summary>
public static class XLuaAutoBuild
{// 步驟名稱與可能方法名的映射表private static readonly Dictionary<string, string[]> XLuaMethods = new Dictionary<string, string[]>{{ "清除生成代碼", new[] { "ClearGen", "ClearGeneratedCode", "ClearGenerateCode", "ClearGenerate", "ClearAll" } },{ "生成所有代碼", new[] { "GenAll", "GenerateAll", "Generate", "GenerateCode" } },{ "熱補丁注入", new[] { "HotfixInject", "InjectHotfix", "HotfixInjection", "InjectHotfix" } }};private static bool TryInvokeXLuaMethod(string stepName){// 獲取所有靜態公共方法var allMethods = AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => {try { return a.GetTypes(); }catch { return Enumerable.Empty<Type>(); }}).SelectMany(t => {try { return t.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); }catch { return Enumerable.Empty<MethodInfo>(); }}).Where(m => m.GetParameters().Length == 0).ToList();// 獲取當前步驟的可能方法名if (!XLuaMethods.TryGetValue(stepName, out var possibleMethodNames)){Debug.LogError($"未配置步驟 '{stepName}' 的方法映射");return false;}// 查找匹配的方法var potentialMethods = new List<MethodInfo>();foreach (var method in allMethods){// 檢查方法名是否在可能的方法名列表中if (possibleMethodNames.Any(name =>method.Name.Equals(name, StringComparison.OrdinalIgnoreCase))){potentialMethods.Add(method);}}if (potentialMethods.Count == 0){Debug.LogError($"未找到匹配 {stepName} 的方法。可能的方法名: {string.Join(", ", possibleMethodNames)}");return false;}// 按類型名排序,優先選擇XLua命名空間中的方法var orderedMethods = potentialMethods.OrderBy(m => m.DeclaringType?.FullName?.Contains("XLua") == true ? 0 : 1).ThenBy(m => m.DeclaringType?.FullName).ToList();// 嘗試所有可能的方法foreach (var method in orderedMethods){try{Debug.Log($"嘗試調用: {method.DeclaringType?.FullName}.{method.Name}()");method.Invoke(null, null);Debug.Log($"{stepName} 成功: {method.DeclaringType?.FullName}.{method.Name}()");return true;}catch (Exception ex){Debug.LogWarning($"嘗試 {method.Name} 失敗: {ex.InnerException?.Message ?? ex.Message}");}}Debug.LogError($"所有匹配方法執行失敗: {stepName}");return false;}[MenuItem("XLua/一鍵生成代碼和熱補丁", false, 0)]public static void AutoGenerateAndInject(){Debug.Log("開始 XLua 自動化構建流程...");bool success = true;// 步驟1: 清除舊代碼success &= ExecuteStep("清除生成代碼");// 步驟2: 生成新代碼success &= ExecuteStep("生成所有代碼");// 步驟3: 熱補丁注入success &= ExecuteStep("熱補丁注入");Debug.Log(success? "XLua 構建流程成功完成!": "XLua 構建流程遇到錯誤!");}private static bool ExecuteStep(string stepName){Debug.Log($"正在執行: {stepName}...");bool result = TryInvokeXLuaMethod(stepName);Debug.Log(result? $"{stepName}完成": $"{stepName}失敗");return result;}
}