重写 Unity 的Toggle组件

依据需求从写 Unity 的 Toggle 组件

代码如下:

using System;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using UnityEngine.UI;

/// 
/// Dropdown 组件扩展
/// 
public class DropdownEx : Dropdown
{

    /// 
    /// Toggle 选择点击回调
    /// 
    public UnityAction<int> OnSelectToggleClick;

    Color nowColor;

    protected override void Awake()
    {
        base.Start();

        ColorUtility.TryParseHtmlString("#1890ff", out nowColor);
    }

    public override void OnPointerClick(PointerEventData eventData)
    {
        base.OnPointerClick(eventData);

        if (!IsInteractable() || !IsActive()) return;

        ScrollRect scrollRect = gameObject.GetComponentInChildren<ScrollRect>();

        Scrollbar scrollbar = scrollRect?.verticalScrollbar;
        if (scrollbar != null && options.Count > 1)
        {
            scrollbar.value = Mathf.Max(0.001f, 1 - (float)value / (options.Count - 1));
        }

        Transform trans = scrollRect?.content;

        if (trans == null && options.Count == 0) return;

        Toggle[] toggles = trans.GetComponentsInChildren<Toggle>();
        SetSelectTextColor(toggles);

        for (int i = 0; i < toggles.Length; i++)
        {
            toggles[i].onValueChanged.AddListener(ison =>
            {
                SetSelectTextColor(toggles);
                if (ison)
                    OnSelectToggleClick?.Invoke(value);
            });
        }
    }

    /// 
    /// 设置选中文本的颜色
    /// 
    /// 
    private void SetSelectTextColor(Toggle[] toggles)
    {
        for (int i = 0; i < toggles.Length; i++)
        {
            if (toggles[i].isOn)
            {
                toggles[i].GetComponentInChildren<Text>().color = nowColor;
            }
            else
            {
                toggles[i].GetComponentInChildren<Text>().color = Color.black;
            }
        }
    }

}

你可能感兴趣的:(unity,游戏引擎)