89 lines
2.7 KiB
C#
89 lines
2.7 KiB
C#
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
using UnityEngine.Events;
|
|
using UnityEngine.EventSystems;
|
|
|
|
namespace Prefab
|
|
{
|
|
public class RightMenuPrefab: Utils.MonoSingleton<RightMenuPrefab>,IPointerExitHandler
|
|
{
|
|
public GameObject menu;
|
|
public ButtonPrefab buttonPrefab;
|
|
|
|
public void Show()
|
|
{
|
|
gameObject.SetActive(true);
|
|
}
|
|
|
|
public void Hide()
|
|
{
|
|
gameObject.SetActive(false);
|
|
}
|
|
|
|
public void Init(List<(string name, UnityAction callback)> buttons)
|
|
{
|
|
if (menu == null || buttonPrefab == null)
|
|
{
|
|
Debug.LogError("Menu or ButtonPrefab is not assigned!");
|
|
return;
|
|
}
|
|
|
|
ClearMenu();
|
|
foreach (var (label, callback) in buttons)
|
|
{
|
|
// 实例化按钮预制体
|
|
var instantiatedButton = Instantiate(buttonPrefab.gameObject, menu.transform);
|
|
var buttonInstance = instantiatedButton.GetComponent<ButtonPrefab>();
|
|
|
|
if (buttonInstance != null)
|
|
{
|
|
// 设置按钮文本
|
|
buttonInstance.Label = label;
|
|
|
|
// 创建一个新的回调函数,包含原始回调和隐藏菜单的操作
|
|
UnityAction wrappedCallback = () =>
|
|
{
|
|
try
|
|
{
|
|
// 执行原始回调
|
|
callback?.Invoke();
|
|
}
|
|
catch (System.Exception e)
|
|
{
|
|
Debug.LogError($"Error executing callback for button '{label}': {e.Message}");
|
|
}
|
|
finally
|
|
{
|
|
// 隐藏菜单
|
|
Hide();
|
|
}
|
|
};
|
|
|
|
// 添加包装后的回调
|
|
buttonInstance.AddListener(wrappedCallback);
|
|
}
|
|
else
|
|
{
|
|
Debug.LogError("Failed to get ButtonPrefab component from instantiated object!");
|
|
}
|
|
}
|
|
}
|
|
public void ClearMenu()
|
|
{
|
|
// 遍历菜单下的所有子对象并销毁它们
|
|
foreach (Transform child in menu.transform)
|
|
{
|
|
Destroy(child.gameObject);
|
|
}
|
|
}
|
|
protected override void OnStart()
|
|
{
|
|
Hide();
|
|
}
|
|
|
|
public void OnPointerExit(PointerEventData eventData)
|
|
{
|
|
Hide();
|
|
}
|
|
}
|
|
} |