using System; using System.Collections.Generic; using System.Linq; using TMPro; using UnityEngine; namespace PhxhSDK { /// /// 文本下拉框 /// /// public class UITextDropdown : UIGameObjectWrapper { /// /// 选中变化回调 /// private readonly Action onValueChanged; /// /// 下拉框 /// private readonly TMP_Dropdown dropdown; private readonly Func data2Text; private readonly TMP_Text text; private int currentSelected; private List listData; public UITextDropdown(GameObject root, GameObject selectTextObject, Action onValueChanged, Func data2Text) : base(root, true) { dropdown = GetItem(); text = GetItem(selectTextObject); if (dropdown == null) DebugUtil.LogError($"cannot find TMP_Dropdown component in {(root == null ? null : root.name)}"); if (text == null) DebugUtil.LogError($"cannot find TMP_Text component in {(selectTextObject == null ? null : selectTextObject.name)}"); this.onValueChanged = onValueChanged; this.data2Text = data2Text; dropdown.onValueChanged.AddListener(OnValueChanged); } public void SetData(IEnumerable collection) { listData ??= new(collection.Count()); listData.Clear(); listData.AddRange(collection); if (dropdown == null) return; dropdown.ClearOptions(); foreach (T item in listData) { TMP_Dropdown.OptionData data = new(); if (data2Text != null) data.text = data2Text(item); dropdown.options.Add(data); } if (listData != null && currentSelected >= 0 && currentSelected < listData.Count) { if (data2Text != null && text != null) text.text = data2Text(listData[currentSelected]); } } public void Clear() { dropdown?.ClearOptions(); } public void SetValue(int value) { currentSelected = value; } private void OnValueChanged(int value) { currentSelected = value; if (listData != null && currentSelected >= 0 && currentSelected < listData.Count) { if (data2Text != null && text != null) text.text = data2Text(listData[currentSelected]); onValueChanged?.Invoke(listData[currentSelected]); } } } }