using System; using System.Collections.Generic; using System.Linq; using TMPro; using UnityEngine; namespace PhxhSDK { public class UIImageDropDown : UIGameObjectWrapper { private readonly Action _onValueChanged; private readonly TMP_Dropdown _dropdown; private readonly Func _data2Text; private readonly Func _data2Img; private readonly TMP_Text _text; private int _currentSelected; private List _datas; public UIImageDropDown(GameObject go, GameObject selectTextObject, Action onValueChanged, Func data2Text,Funcdata2Img) : base(go, true) { _dropdown = GetItem(); _text = GetItem(selectTextObject); if (_dropdown == null) { DebugUtil.LogError("cannot find TMP_Dropdown component in {0}", go?.name); } if (_text == null) { DebugUtil.LogError("cannot find TMP_Text component in {0}", selectTextObject?.name); } _onValueChanged = onValueChanged; _data2Img = data2Img; _data2Text = data2Text; _dropdown.onValueChanged.AddListener(_OnValueChanged); } public void SetData(IEnumerable collection) { _datas?.Clear(); var enumerable = collection.ToList(); _datas = new List(enumerable); if (_dropdown != null) { _dropdown.ClearOptions(); foreach (var item in enumerable) { var data = new TMP_Dropdown.OptionData(); if (_data2Img != null) { data.image = _data2Img(item); } _dropdown.options.Add(data); } } } public void Clear() { _dropdown?.ClearOptions(); } private void _OnValueChanged(int value) { _currentSelected = value; if (_datas != null && _currentSelected >= 0 && _currentSelected < _datas.Count) { if (_data2Text != null && _text != null) { _text.text = _data2Text(_datas[_currentSelected]); } _onValueChanged?.Invoke(_datas[_currentSelected]); } } } }