using System; using System.Reflection; using UnityEngine; using UnityEngine.UI; using TMPro; namespace MeowmentDebugTool { /// /// 自定义按钮模块 - 通过反射加载标记为DebugButton的方法 /// public class CustomButtonsModule : IDebugModule { #region 字段 private GameObject customButtonsPage; private RectTransform buttonContainer; private GameObject buttonPrefab; private ScrollRect buttonsScrollRect; // 自定义按钮回调 private Action customButtonCallback; // 保存的SDF字体资源 private TMP_FontAsset savedFontAsset = null; // 关闭窗口回调 private Action onCloseWindowCallback; #endregion #region 构造函数 public CustomButtonsModule(GameObject page, RectTransform container, GameObject prefab, ScrollRect scrollRect, Action closeWindowCallback) { customButtonsPage = page; buttonContainer = container; buttonPrefab = prefab; buttonsScrollRect = scrollRect; onCloseWindowCallback = closeWindowCallback; } #endregion #region IDebugModule 实现 public void Initialize() { Debug.Log("[CustomButtonsModule] 初始化自定义按钮模块..."); LoadCustomButtons(); } public GameObject GetPage() { return customButtonsPage; } public string GetModuleName() { return "自定义按钮"; } #endregion #region 公共方法 /// /// 设置SDF字体 /// public void SetSDFFont(TMP_FontAsset fontAsset) { savedFontAsset = fontAsset; } /// /// 设置自定义按钮回调 /// public void SetCustomButtonCallback(Action callback) { customButtonCallback = callback; } /// /// 重新加载自定义按钮 /// public void ReloadCustomButtons() { LoadCustomButtons(); } #endregion #region 私有方法 /// /// 加载所有自定义按钮(使用反射) /// private void LoadCustomButtons() { if (buttonContainer == null || buttonPrefab == null) { Debug.LogWarning("[CustomButtonsModule] 按钮容器或按钮预制件未设置"); return; } // 清空现有按钮 foreach (Transform child in buttonContainer) { UnityEngine.Object.Destroy(child.gameObject); } // 查找所有标记为DebugButton的方法 var assemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (var assembly in assemblies) { try { var types = assembly.GetTypes(); foreach (var type in types) { var methods = type.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); foreach (var method in methods) { var attribute = method.GetCustomAttribute(); if (attribute != null) { CreateCustomButton(method, attribute); } } } } catch (Exception e) { // 某些程序集可能无法访问,跳过 Debug.LogWarning($"[CustomButtonsModule] 无法访问程序集 {assembly.FullName}: {e.Message}"); } } } private void CreateCustomButton(MethodInfo method, DebugButtonAttribute attribute) { GameObject buttonObj = UnityEngine.Object.Instantiate(buttonPrefab, buttonContainer); Button button = buttonObj.GetComponent