UGUI ソース コード解析 3: EventData

1. EventData の概要

EventData は主に、イベント システムでデータをカプセル化するために使用されます。主に以下のカテゴリで構成されています。

1.AbstractEventData: イベントデータの抽象基本クラスで、主にイベントデータが使用されているかどうかを判断するために使用されます。

2.BaseEventData: AbstractEventData から継承されたイベント データベースの基本クラスで、主にいくつかのイベント システム ロールの参照をカプセル化します。

3. AxisEventData: BaseEventData から継承された軸イベント データ クラスで、主に軸イベントに関連するデータをカプセル化します. このタイプは、主にハンドルとキーボードの軸を制御するときに使用されます.

3. PointerEventData: BaseEventData から継承されたポインター イベント データ型は、主にマウス クリックおよびタッチ イベント (クリック、リフト、ドラッグなど) に関連するデータをカプセル化します。UGUI のほとんどのイベント データ型は PointerEventData 型です。

2. PointerEventData の主な属性

属性

例証する

public GameObject ポインタEnter

現在 PointEnter イベントを受け取っているオブジェクト

public GameObject pointerPress

現在、PoninterPress イベントを受け取っているオブジェクト

public GameObject lastPress

OnPointPress イベントを受け取った最後のオブジェクト

public GameObject rawPointerPress

現在のプレス イベントのゲームオブジェクト (破棄またはクローズなど、イベントをトリガーできない場合も含む)

public GameObject pointerDrag

現在 OnPointDrag イベントを受け取っているオブジェクト

public RaycastResult ポインターCurrentRaycast

ゲームオブジェクト、UI レベルなど、現在レイ検出イベントに応答している情報は、ドラッグなどの操作で変更されます。

public RaycastResult ポインターPressRaycast

ポインターが押されたときにレイ検出に応答する UI は、クリック イベントで変化しません。

public List<GameObject> ホバー

マウスオーバー時の pointerEnter とそのすべての親と祖先によって形成されるオブジェクトのリスト

public bool 適格なForClick

この時点でイベントが修飾されたクリックであるかどうかは、後で確認できます. クリック イベントが処理される前に移動イベントが処理されると、この状態はキャンセルされ、クリック イベントは処理できません. この状態は、ScrollRect を実行するためのキーです.スライドとクリックを同時に行うことができます。

public int ポインター ID

ポインタのインジケータ、マウスを使用している場合、-1 は左ボタンを意味します -2 は右ボタンを意味します -3 は Zhongjian を意味します モバイル端末のタッチスクリーンを使用している場合は、0 からサポートされている最大タッチ数までを意味しますデバイスによって

パブリック Vector2 位置

ポインターの位置、ウィンドウの左下が原点

パブリック Vector2 デルタ

現在または最後のクリック時のポインターの位置

public Vector3 worldPosition

光線によって最初に検出されたオブジェクトのワールド座標

public Vector3 worldNormal

レイは最初のオブジェクトの法線を検出します

public float clickTime

クリック イベントが最後に送信された時刻

public int クリック数

連続クリック

public Vector2 scrollDelta

前のフレームからこのフレームへのスクロールの変化量

public bool useDragThreshold

ドラッグしきい値を有効にするかどうか

パブリックブールドラッグ

現在ドラッグ状態かどうか

public InputButton ボタン

現在のイベントのボタン

public bool IsPointerMoving()

前のフレームとこのフレームの間に動きがあるかどうか

public bool IsScrolling()

前のフレームとこのフレームの間でスクロールが発生したかどうか

3. EventData の完全なソース コードとコメントの分析:

3.1.BaseEventData.csとAbstractEventData.cs

namespace UnityEngine.EventSystems
{
    /// <summary>
    /// A class that can be used for sending simple events via the event system.
    /// </summary>
    public abstract class AbstractEventData
    {
        protected bool m_Used;      //是否使用

        /// <summary>
        /// Reset the event.
        /// </summary>
        public virtual void Reset()
        {
            m_Used = false;
        }

        /// <summary>
        /// Use the event.
        /// </summary>
        /// <remarks>
        /// Internally sets a flag that can be checked via used to see if further processing should happen.
        /// </remarks>
        public virtual void Use()
        {
            m_Used = true;
        }

        /// <summary>
        /// Is the event used?
        /// </summary>
        public virtual bool used
        {
            get { return m_Used; }
        }
    }

    /// <summary>
    /// A class that contains the base event data that is common to all event types in the new EventSystem.
    /// </summary>
    public class BaseEventData : AbstractEventData
    {
        private readonly EventSystem m_EventSystem;     //当前生效的EventSystem
        public BaseEventData(EventSystem eventSystem)
        {
            m_EventSystem = eventSystem;
        }

        /// <summary>
        /// >A reference to the BaseInputModule that sent this event.
        /// </summary>
        public BaseInputModule currentInputModule       //当前生效的输入模块
        {
            get { return m_EventSystem.currentInputModule; }
        }

        /// <summary>
        /// The object currently considered selected by the EventSystem.
        /// </summary>
        public GameObject selectedObject        //当前选中的对象
        {
            get { return m_EventSystem.currentSelectedGameObject; }
            set { m_EventSystem.SetSelectedGameObject(value, this); }
        }
    }
}

3.2.AxisEventData.cs

namespace UnityEngine.EventSystems
{
    /// <summary>
    /// Event Data associated with Axis Events (Controller / Keyboard).
    /// </summary>
    public class AxisEventData : BaseEventData
    {
        /// <summary>
        /// Raw input vector associated with this event.
        /// </summary>
        public Vector2 moveVector { get; set; }     //原始的输入向量值.即键盘和手柄输入的轴向值

        /// <summary>
        /// MoveDirection for this event.
        /// </summary>
        public MoveDirection moveDir { get; set; }      //移动方向 共有五个值:Left, Up, Right, Down, None

        public AxisEventData(EventSystem eventSystem)
            : base(eventSystem)
        {
            moveVector = Vector2.zero;
            moveDir = MoveDirection.None;
        }
    }
}

3.3.PointerEventData.cs

using System;
using System.Text;
using System.Collections.Generic;

namespace UnityEngine.EventSystems
{
    /// <summary>
    /// Each touch event creates one of these containing all the relevant information.
    /// </summary>
    public class PointerEventData : BaseEventData
    {
        /// <summary>
        /// Input press tracking.
        /// </summary>
        public enum InputButton
        {
            /// <summary>
            /// Left button
            /// </summary>
            Left = 0,       //左键

            /// <summary>
            /// Right button.
            /// </summary>
            Right = 1,      //右键

            /// <summary>
            /// Middle button
            /// </summary>
            Middle = 2      //中键
        }

        /// <summary>
        /// The state of a press for the given frame.
        /// </summary>
        public enum FramePressState     //每个键在当前帧的状态
        {
            /// <summary>
            /// Button was pressed this frame.
            /// </summary>
            Pressed,        //按下

            /// <summary>
            /// Button was released this frame.
            /// </summary>
            Released,       //抬起

            /// <summary>
            /// Button was pressed and released this frame.
            /// </summary>
            PressedAndReleased,     //按下后抬起

            /// <summary>
            /// Same as last frame.
            /// </summary>
            NotChanged      //无变化
        }

        /// <summary>
        /// The object that received 'OnPointerEnter'.
        /// </summary>
        public GameObject pointerEnter { get; set; }    //当前已接收到PointEnter事件的对象

        // The object that received OnPointerDown
        private GameObject m_PointerPress;      //当前已接收到PoninterPress事件的对象

        /// <summary>
        /// The raw GameObject for the last press event. This means that it is the 'pressed' GameObject even if it can not receive the press event itself.
        /// </summary>
        public GameObject lastPress { get; private set; }       //上一个接收到OnPointPress事件的对象

        /// <summary>
        /// The object that the press happened on even if it can not handle the press event.
        /// </summary>
        public GameObject rawPointerPress { get; set; }     //当前presss事件中的GameObject,即使已经无法触发事件,例如被销毁或者关闭

        /// <summary>
        /// The object that is receiving 'OnDrag'.
        /// </summary>
        public GameObject pointerDrag { get; set; }     //当前接收到OnPointDrag事件的物体

        /// <summary>
        /// RaycastResult associated with the current event.
        /// </summary>
        public RaycastResult pointerCurrentRaycast { get; set; }    //当前响应射线检测事件的信息,例如这个gameobject,ui层级等,会随着拖动等操作变化

        /// <summary>
        /// RaycastResult associated with the pointer press.
        /// </summary>
        public RaycastResult pointerPressRaycast { get; set; }      //指针按下时响应射线检测的ui,在一次点击事件中不会改变

        public List<GameObject> hovered = new List<GameObject>();       //鼠标悬停时, pointerEnter和其所有父节点和祖先节点形成的对象列表

        /// <summary>
        /// Is it possible to click this frame
        /// </summary>
        public bool eligibleForClick { get; set; }      //此时事件是否是合格的点击, 后面可以看到, 如果在处理点击事件之前处理了移动事件则会取消此状态导致点击事件无法处理, 这个状态是ScrollRect能够同时滑动和点击的关键.

        /// <summary>
        /// Id of the pointer (touch id).
        /// </summary>
        public int pointerId { get; set; }      //指针的标识,如果使用的是鼠标则-1表示左键 -2表示右键 -3表示中建 如果使用的移动端触屏则表示从0开始到设备支持的最大触摸个数

        /// <summary>
        /// Current pointer position.
        /// </summary>
        public Vector2 position { get; set; }       //指针的位置, 窗口的左下角为原点

        /// <summary>
        /// Pointer delta since last update.
        /// </summary>
        public Vector2 delta { get; set; }      //上一帧到这一帧之间的指针的位移变化量,一般用来判断移动方向

        /// <summary>
        /// Position of the press.
        /// </summary>
        public Vector2 pressPosition { get; set; }      //当前或者最后一次点击时指针的位置

        /// <summary>
        /// World-space position where a ray cast into the screen hits something
        /// </summary>

        [Obsolete("Use either pointerCurrentRaycast.worldPosition or pointerPressRaycast.worldPosition")]
        public Vector3 worldPosition { get; set; }      //射线检测到第一个物体的世界坐标

        /// <summary>
        /// World-space normal where a ray cast into the screen hits something
        /// </summary>
        [Obsolete("Use either pointerCurrentRaycast.worldNormal or pointerPressRaycast.worldNormal")]
        public Vector3 worldNormal { get; set; }        //射线检测到第一个物体的法线

        /// <summary>
        /// The last time a click event was sent. Used for double click
        /// </summary>
        public float clickTime { get; set; }        //上次发送点击事件的时间

        /// <summary>
        /// Number of clicks in a row.
        /// </summary>
        /// <example>
        /// <code>
        /// using UnityEngine;
        /// using System.Collections;
        /// using UnityEngine.UI;
        /// using UnityEngine.EventSystems;// Required when using Event data.
        ///
        /// public class ExampleClass : MonoBehaviour, IPointerDownHandler
        /// {
        ///     public void OnPointerDown(PointerEventData eventData)
        ///     {
        ///         //Grab the number of consecutive clicks and assign it to an integer varible.
        ///         int i = eventData.clickCount;
        ///         //Display the click count.
        ///         Debug.Log(i);
        ///     }
        /// }
        /// </code>
        /// </example>
        public int clickCount { get; set; }     //连续点击次数

        /// <summary>
        /// The amount of scroll since the last update.
        /// </summary>
        public Vector2 scrollDelta { get; set; }        //上一帧到这一帧之间的滚动变化量

        /// <summary>
        /// Should a drag threshold be used?
        /// </summary>
        /// <remarks>
        /// If you do not want a drag threshold set this to false in IInitializePotentialDragHandler.OnInitializePotentialDrag.
        /// </remarks>
        public bool useDragThreshold { get; set; }      //是否启动拖拽阈值

        /// <summary>
        /// Is a drag operation currently occuring.
        /// </summary>
        public bool dragging { get; set; }      //当前是否处于拖拽状态

        /// <summary>
        /// The EventSystems.PointerEventData.InputButton for this event.
        /// </summary>
        public InputButton button { get; set; }     //当前事件的按钮

        public PointerEventData(EventSystem eventSystem) : base(eventSystem)
        {
            eligibleForClick = false;

            pointerId = -1;
            position = Vector2.zero; // Current position of the mouse or touch event
            delta = Vector2.zero; // Delta since last update
            pressPosition = Vector2.zero; // Delta since the event started being tracked
            clickTime = 0.0f; // The last time a click event was sent out (used for double-clicks)
            clickCount = 0; // Number of clicks in a row. 2 for a double-click for example.

            scrollDelta = Vector2.zero;
            useDragThreshold = true;
            dragging = false;
            button = InputButton.Left;
        }

        /// <summary>
        /// Is the pointer moving.
        /// </summary>
        public bool IsPointerMoving()       //上一帧到这一帧之间是否发生了移动
        {
            return delta.sqrMagnitude > 0.0f;
        }

        /// <summary>
        /// Is scroll being used on the input device.
        /// </summary>
        public bool IsScrolling()       //上一帧到这一帧之间是否发生了滚动
        {
            return scrollDelta.sqrMagnitude > 0.0f;
        }

        /// <summary>
        /// The camera associated with the last OnPointerEnter event.
        /// </summary>
        public Camera enterEventCamera
        {
            get { return pointerCurrentRaycast.module == null ? null : pointerCurrentRaycast.module.eventCamera; }
        }       //与最后一个OnPointerEnter事件关联的摄像头。这个主要用于多相机混合的时候判断当前按钮的事件是由哪个相机触发的

        /// <summary>
        /// The camera associated with the last OnPointerPress event.
        /// </summary>
        public Camera pressEventCamera
        {
            get { return pointerPressRaycast.module == null ? null : pointerPressRaycast.module.eventCamera; }
        }       //与最后一个OnPointerPress事件关联的摄像头,当没有接收OnPointerDown的游戏物体会报空

        /// <summary>
        /// The GameObject that received the OnPointerDown.
        /// </summary>
        public GameObject pointerPress
        {
            get { return m_PointerPress; }
            set
            {
                if (m_PointerPress == value)
                    return;

                lastPress = m_PointerPress;
                m_PointerPress = value;
            }
        }

        public override string ToString()
        {
            var sb = new StringBuilder();
            sb.AppendLine("<b>Position</b>: " + position);
            sb.AppendLine("<b>delta</b>: " + delta);
            sb.AppendLine("<b>eligibleForClick</b>: " + eligibleForClick);
            sb.AppendLine("<b>pointerEnter</b>: " + pointerEnter);
            sb.AppendLine("<b>pointerPress</b>: " + pointerPress);
            sb.AppendLine("<b>lastPointerPress</b>: " + lastPress);
            sb.AppendLine("<b>pointerDrag</b>: " + pointerDrag);
            sb.AppendLine("<b>Use Drag Threshold</b>: " + useDragThreshold);
            sb.AppendLine("<b>Current Rayast:</b>");
            sb.AppendLine(pointerCurrentRaycast.ToString());
            sb.AppendLine("<b>Press Rayast:</b>");
            sb.AppendLine(pointerPressRaycast.ToString());
            return sb.ToString();
        }
    }
}

おすすめ

転載: blog.csdn.net/m0_57771536/article/details/128606948