Unity GUI 事件系统

2022年5月8日 2541点热度 1人点赞 0条评论

前言

Unity 专为GUI对象建立了一个事件系统,用于游戏场景中的UI响应系统的一些事件。起初读到文档的时候我还是比较疑惑的,因为大多数事件和MonoBehaviour提供的事件回调都是相同的,那么为啥还要单独出一套呢?之后我又读了了下关于MonoBehaviour的文档, 原来一些回调事件需要对象有collider对象才能被触发,所以总不能为了触发回调事件也给UI对象也添加一个Collider吧。

支持哪些事件

这些接口都定义在UnityEngine.EventSystems命名空间中,但是在API文档中却没有找到相应的介绍,也是挺奇怪。

  • IPointerEnterHandler - OnPointerEnter - 当指针进入对象时调用
  • IPointerExitHandler - OnPointerExit - 当指针退出对象时调用
  • IPointerDownHandler - OnPointerDown - 在对象上按下指针时调用
  • IPointerUpHandler - OnPointerUp - 松开指针时调用(在指针正在点击的游戏对象上调用)
  • IPointerClickHandler - OnPointerClick - 在同一对象上按下再松开指针时调用
  • IInitializePotentialDragHandler - OnInitializePotentialDrag - 在找到拖动目标时调用,可用于初始化值
  • IBeginDragHandler - OnBeginDrag - 即将开始拖动时在拖动对象上调用
  • IDragHandler - OnDrag - 发生拖动时在拖动对象上调用
  • IEndDragHandler - OnEndDrag - 拖动完成时在拖动对象上调用
  • IDropHandler - OnDrop - 在拖动目标对象上调用
  • IScrollHandler - OnScroll - 当鼠标滚轮滚动时调用
  • IUpdateSelectedHandler - OnUpdateSelected - 每次勾选时在选定对象上调用
  • ISelectHandler - OnSelect - 当对象成为选定对象时调用
  • IDeselectHandler - OnDeselect - 取消选择选定对象时调用
  • IMoveHandler - OnMove - 发生移动事件(上、下、左、右等)时调用
  • ISubmitHandler - OnSubmit - 按下 Submit 按钮时调用
  • ICancelHandler - OnCancel - 按下 Cancel 按钮时调用

要使相应的事件,只需要继承接口,实现接口函数即可。

实现游戏中对GUI对象的拖拽

只需要新建一个脚本对象,继承MonoBehaviour和IDragHandler,然后再onDrag()函数中实现对象跟随鼠标移动的功能即可。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class DragObject : MonoBehaviour,IDragHandler
{

    public void OnDrag(PointerEventData eventData)
    {
        gameObject.transform.position = eventData.position;
    }
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

    }
}

在场景中创建一个GUI对象,将脚本作为组件添加。

Unity_Script2

注意: 这些接口只在GUI对象上有效,在其他对象上不会触发事件

大脸猫

这个人虽然很勤快,但什么也没有留下!

文章评论