TH1/My project/Assets/Scripts/UI/ChooseUI/ToggleButtonGroupController.cs
2025-07-09 17:23:17 +08:00

89 lines
2.7 KiB
C#

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Collections.Generic;
using Logic.CrashSight;
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(0x00, 0x00, 0x00, 112); // #000000, alpha 112
private readonly Color normalColor = new Color32(0x00, 0x00, 0x00, 1); // #000000, alpha 1
void Start()
{
selectedButton = null;
buttonGroup = transform.Find(buttonGroupName);
if (buttonGroup == null)
{
LogSystem.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));
Image bgImage = btn.transform.Find("BG")?.GetComponent<Image>();
if (bgImage != null)
{
bgImage.color = (btn == selectedButton) ? selectedColor : normalColor;
}
}
}
// 设置默认选项
if (buttons.Count > 0)
{
int deft = buttons.Count - 1;
//地图默认 18x18
if (gameObject.name == "MapSize" && deft >= 3)
deft = 3;
//玩家默认 8
if (gameObject.name == "EnemyCount" && deft >= 6)
deft = 6;
//难度默认 LUNATIC
if (gameObject.name == "Difficulty" && deft >= 3)
deft = 3;
//模式默认 征服模式
if (gameObject.name == "Mode" && deft >= 1)
deft = 1;
OnButtonClicked(buttons[deft]);
}
}
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 : "";
}
}