45 lines
1.7 KiB
C#
45 lines
1.7 KiB
C#
using System.Collections.Generic;
|
||
using UnityEngine;
|
||
using UnityEngine.Events;
|
||
using TMPro;
|
||
|
||
namespace BaseGames.UI
|
||
{
|
||
/// <summary>
|
||
/// 下拉控件封装:TMP_Dropdown + 一行式 <see cref="Bind"/>(填充选项 / 设当前项 / 接回调),
|
||
/// 消除设置面板里重复的 ClearOptions/AddOptions/RefreshShownValue 样板。
|
||
/// 选项文本可由调用方先经本地化(<c>LocalizationManager.Get</c>)解析后传入。
|
||
/// </summary>
|
||
[DisallowMultipleComponent]
|
||
public class UIDropdown : MonoBehaviour
|
||
{
|
||
[SerializeField] private TMP_Dropdown _dropdown;
|
||
|
||
public TMP_Dropdown Dropdown => _dropdown;
|
||
public int Value => _dropdown != null ? _dropdown.value : 0;
|
||
|
||
/// <summary>填充选项、设当前选中项并接变更回调。</summary>
|
||
public void Bind(IEnumerable<string> options, int index, UnityAction<int> onChanged)
|
||
{
|
||
if (_dropdown == null) return;
|
||
_dropdown.onValueChanged.RemoveAllListeners();
|
||
_dropdown.ClearOptions();
|
||
|
||
var list = options as List<string> ?? new List<string>(options);
|
||
_dropdown.AddOptions(list);
|
||
_dropdown.value = Mathf.Clamp(index, 0, Mathf.Max(0, list.Count - 1));
|
||
_dropdown.RefreshShownValue();
|
||
|
||
_dropdown.onValueChanged.AddListener(i => onChanged?.Invoke(i));
|
||
}
|
||
|
||
/// <summary>不触发回调地设置当前选中项(用于外部状态同步)。</summary>
|
||
public void SetIndexSilent(int index)
|
||
{
|
||
if (_dropdown == null) return;
|
||
_dropdown.SetValueWithoutNotify(Mathf.Clamp(index, 0, Mathf.Max(0, _dropdown.options.Count - 1)));
|
||
_dropdown.RefreshShownValue();
|
||
}
|
||
}
|
||
}
|