编程语言
首页 > 编程语言> > UGUI 源码解读-EventSystem

UGUI 源码解读-EventSystem

作者:互联网

EventSystem事件系统的源码目录结构如下:大致可分为EventData、InputModules、Raycasters、EventSystem、ExecuteEvents。
在这里插入图片描述

EventSystem的职责:

  1. 管理和处理输入事件(InputModule)
  2. 调用Raycaster发起射线检测,获取输入事件投射到的物体
  3. 将事件发送给投射物体处理。

每个场景一般有且只有一个EventSystem,EventSystem上一般会挂一个InputModule模块。
在这里插入图片描述

EventData

在这里插入图片描述

InputModules

在这里插入图片描述

EventSystem的Update函数中,先通过TickModules调用InputModule的UpdateModule函数,然后调用Process函数分发事件。

在这里插入图片描述

在这里插入图片描述

Raycasters

在事件系统中充当捕获物体的角色,管理射线,为InputModule提供GameObject

被射线检测到的结果会包装成RaycastResult返回:

在这里插入图片描述

什么时候会发起射线检测?

EventSystem中有一个RaycastAll函数,依次调用Raycast函数发起射线检测。

在这里插入图片描述

在BaseInputModule的GetTouchPointerEventDataGetMousePointerEventData函数中通过eventSystem.RaycastAll开始射线检测。

        protected PointerEventData GetTouchPointerEventData(Touch input, out bool pressed, out bool released)
        {
            PointerEventData pointerData;
            var created = GetPointerData(input.fingerId, out pointerData, true);
            //....省略部分代码
            if (input.phase == TouchPhase.Canceled)
            {
                pointerData.pointerCurrentRaycast = new RaycastResult();
            }
            else
            {
               //发起射线检测 
               eventSystem.RaycastAll(pointerData, m_RaycastResultCache);

                var raycast = FindFirstRaycast(m_RaycastResultCache);
                pointerData.pointerCurrentRaycast = raycast;
                m_RaycastResultCache.Clear();
            }
            return pointerData;
        }


        protected virtual MouseState GetMousePointerEventData(int id)
        {
            // Populate the left button...
            PointerEventData leftData;
            var created = GetPointerData(kMouseLeftId, out leftData, true);
            //....省略部分代码
            //发起射线检测 
            eventSystem.RaycastAll(leftData, m_RaycastResultCache);
            var raycast = FindFirstRaycast(m_RaycastResultCache);
            leftData.pointerCurrentRaycast = raycast;
            m_RaycastResultCache.Clear();
            //....省略部分代码
            return m_MouseState;
        }

EventSystemHandler

被射线检测到的GameObject不一定直接参与事件处理,一般会检测当前物体或者其父物体上的脚本是否实现了IEventSystemHandler接口。

public interface IPointerEnterHandler : IEventSystemHandler
{
    /// <summary>
    /// Use this callback to detect pointer enter events
    /// </summary>
    void OnPointerEnter(PointerEventData eventData);
}

接口主要分为三大类:

ExecuteEvents

事件执行器,封装了事件执行相关的逻辑。

在这里插入图片描述

详细执行过程可看ProcessTouchEvents和ProcessMouseEvent两个函数的逻辑。

标签:pointerData,函数,射线,EventSystem,PointerEventData,源码,事件,UGUI
来源: https://blog.csdn.net/maplejaw_/article/details/117199021