Unity 改寫Dropdown支援多次點選同一選項均回撥
阿新 • • 發佈:2021-12-10
1.UGUI自帶的Dropdown,建立之後,執行場景預設選擇第一個選項,再次點選第一個選項也不會觸發,因專案需求,所以要改成多次點選有效
2.建立下拉框(Dropdown),建立好之後刪除Dropdown元件
3.建立c#指令碼 (重寫下拉框,新增一個bool變數用來控制)
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; public class DropdownEx : 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(); } }
4.把指令碼新增到下拉框上面會出現新的元件(如下圖所示)
箭頭處需要自己拖上去
5.建立一個Editor指令碼放在Editor資料夾下
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEditor; using UnityEditor.UI; [CustomEditor(typeof(DropdownEx), true)] [CanEditMultipleObjects] public class DropdowmExEditor : 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(); } }
需要重複點選就勾選上m_AlwaysCallback變數
❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤
❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤
❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤