改寫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);
        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();
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM