欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

改写Unity DropDown 支持多次点击同一选项均回调

发布时间:2025/3/21 编程问答 52 豆豆
生活随笔 收集整理的这篇文章主要介绍了 改写Unity DropDown 支持多次点击同一选项均回调 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

[很久前的一个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);elsevalue = 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();} }

 

转载于:https://www.cnblogs.com/wmalloc/p/7234319.html

总结

以上是生活随笔为你收集整理的改写Unity DropDown 支持多次点击同一选项均回调的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。