其他分享
首页 > 其他分享> > Unity 改写Dropdown支持多次点击同一选项均回调

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

作者:互联网

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 变量

 

 

 

❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤

❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤

❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤

 

标签:UnityEngine,Dropdown,void,改写,Unity,AlwaysCallback,using,public
来源: https://www.cnblogs.com/qq2351194611/p/15670378.html