61 lines
1.8 KiB
C#
61 lines
1.8 KiB
C#
using UnityEngine;
|
|
using UnityEngine.UI;
|
|
using UnityEngine.EventSystems;
|
|
using System.Collections.Generic;
|
|
|
|
public class ToggleButtonGroupController : MonoBehaviour
|
|
{
|
|
public string buttonGroupName = "ButtonGroup";
|
|
|
|
private Transform buttonGroup;
|
|
private List<Button> buttons = new List<Button>();
|
|
private Button selectedButton;
|
|
|
|
// 高亮与默认颜色
|
|
private readonly Color selectedColor = new Color32(0x3E, 0xAB, 0x02, 255); // #3EAB02
|
|
private readonly Color normalColor = new Color32(0x00, 0x00, 0x00, 112); // #000000, alpha 112
|
|
|
|
void Start()
|
|
{
|
|
buttonGroup = transform.Find(buttonGroupName);
|
|
if (buttonGroup == null)
|
|
{
|
|
Debug.LogError($"ButtonGroup '{buttonGroupName}' not found under {gameObject.name}");
|
|
return;
|
|
}
|
|
|
|
// 查找所有按钮并绑定点击事件
|
|
foreach (Transform child in buttonGroup)
|
|
{
|
|
Button btn = child.GetComponent<Button>();
|
|
if (btn != null)
|
|
{
|
|
buttons.Add(btn);
|
|
btn.onClick.AddListener(() => OnButtonClicked(btn));
|
|
}
|
|
}
|
|
|
|
// 默认选中第一个
|
|
if (buttons.Count > 0)
|
|
OnButtonClicked(buttons[0]);
|
|
}
|
|
|
|
private void OnButtonClicked(Button clickedButton)
|
|
{
|
|
selectedButton = clickedButton;
|
|
|
|
foreach (Button btn in buttons)
|
|
{
|
|
Image bgImage = btn.transform.Find("BG")?.GetComponent<Image>();
|
|
if (bgImage != null)
|
|
{
|
|
bgImage.color = (btn == selectedButton) ? selectedColor : normalColor;
|
|
}
|
|
}
|
|
}
|
|
|
|
public string GetSelectedButtonName()
|
|
{
|
|
return selectedButton != null ? selectedButton.name : "";
|
|
}
|
|
} |