[很久前的一个Note,不知道现在的Unity Dropdown是否已经支持该特性]
Unity UGUI是开源的: https://bitbucket.org/Unity-Technologies/ui
可以下载到UI的代码阅读并改写
下面的DropdownEx类在Dropdown基础上,增加一个m_AlwaysCallback 变量,勾选后每次点击都会触发回调
using System; using System.Collections; using System.Collections.Generic; using UnityEngine.Events; using UnityEngine.EventSystems; using UnityEngine.UI.CoroutineTween; using UnityEngine.UI; using UnityEngine; public class DropdownEx : Dropdown { public bool m_AlwaysCallback = false; public void Show() { base.Show(); Transform toggleRoot = transform.FindChild("Dropdown List/Viewport/Content"); Toggle[] toggleList = toggleRoot.GetComponentsInChildren<Toggle>(false); for(int i = 0; i < toggleList.Length; i++) { Toggle temp = toggleList[i]; temp.onValueChanged.RemoveAllListeners(); temp.isOn = false; temp.onValueChanged.AddListener(x => OnSelectItemEx(temp)); } } public override void OnPointerClick(PointerEventData eventData) { Show(); } public void OnSelectItemEx(Toggle toggle) { if (!toggle.isOn) { toggle.isOn = true; return; } int selectedIndex = -1; Transform tr = toggle.transform; Transform parent = tr.parent; for (int i = 0; i < parent.childCount; i++) { if (parent.GetChild(i) == tr) { // Subtract one to account for template child. selectedIndex = i - 1; break; } } if (selectedIndex < 0) return; if (value == selectedIndex && m_AlwaysCallback) onValueChanged.Invoke(value); else value = selectedIndex; Hide(); } }
补充下Editor脚本
using UnityEngine.UI; using UnityEditor; using UnityEditor.UI; [CustomEditor(typeof(DropdownEx), true)] [CanEditMultipleObjects] public class DropdownExEditor : DropdownEditor { SerializedProperty m_AlwaysCallback; protected override void OnEnable() { base.OnEnable(); m_AlwaysCallback = serializedObject.FindProperty("m_AlwaysCallback"); } public override void OnInspectorGUI() { base.OnInspectorGUI(); EditorGUILayout.PropertyField(m_AlwaysCallback); serializedObject.ApplyModifiedProperties(); } }