Unity —— Dropdown 多次重复点击返回事件 UI_AlwaysCallback_Dropdown (转)
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; /// <summary> /// 每次都点击都回调 Dropdown /// </summary> public class UI_AlwaysCallback_Dropdown : Dropdown { public bool m_AlwaysCallback = false; public void ShowController() { base.Show(); Transform toggleRoot = transform.Find("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) { ShowController(); } 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 UnityEditor; using UnityEditor.UI; [CustomEditor(typeof(UI_AlwaysCallback_Dropdown), true)] [CanEditMultipleObjects] public class UI_AlwaysCallback_Dropdown_Editor : 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(); } }
转:https://www.cnblogs.com/qq2351194611/p/15670378.html