| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 |
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using TMPro;
- using UnityEngine;
- using UnityEngine.UI;
- namespace AppUI.Util.Group
- {
- public class BtnGroupSelector : MonoBehaviour
- {
- Action<int> onSelect;
- int currentIndex = -1;
- public void Init(
- string[] texts,
- int selectIndex,
- Action<int> callback)
- {
- currentIndex = selectIndex;
- onSelect = callback;
- Render(texts);
- for (int i = 0; i < transform.childCount; i++)
- {
- int index = i;
- var btn =
- transform.GetChild(i)
- .GetComponentInChildren<Button>();
- btn.onClick.RemoveAllListeners();
- btn.onClick.AddListener(() =>
- {
- Select(index);
- });
- }
- }
- void Select(int index)
- {
- if (currentIndex == index)
- return;
- currentIndex = index;
- onSelect?.Invoke(index);
- RefreshState();
- }
- void Render(string[] texts)
- {
- for (int i = 0; i < transform.childCount; i++)
- {
- var item =
- transform.GetChild(i)
- .GetComponent<SelectItem>();
- item.SetData(
- texts[i],
- i == currentIndex);
- }
- }
- void RefreshState()
- {
- for (int i = 0; i < transform.childCount; i++)
- {
- var item =
- transform.GetChild(i)
- .GetComponent<SelectItem>();
- item.SetData(
- item.GetComponentInChildren<TMP_Text>().text,
- i == currentIndex);
- }
- }
- }
- }
|