Unity: UGUI之回调事件Event

Event事件回调:


一个场景当中只能有一个EventSystem,并且需要BaseInputModule组件

才能协助工作。

UI中触发事件回调可以在组件中存在,也有的单拿出来处理回调事件.在处理回调的脚本中,要引入项目应的命名空间和相关的接口,使用什么接口就引入那个,并实现其方法.

命名空间引入: using UnityEngine.EventSystems;

常用的回调事件如下所示:


Demo1:使用UGUI的回调函数实现物体随着鼠标的拖拽效果

Demo2:实现鼠标移动到按钮上,按钮放大的效果

 
     
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. using UnityEngine.EventSystems;
  6. public class UI_Event_Drag :MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
  7. ,IDragHandler
  8. {
  9.     GameObject button;
  10.     GameObject image;
  11. private void Awake()
  12. {
  13.         button = GameObject.Find("Button");
  14.         image = GameObject.Find("Image");
  15. }
  16. public void OnDrag(PointerEventData eventData)
  17.     {
  18.         image.transform.position = eventData.position;
  19.     }
  20.  
  21.     public void OnPointerEnter(PointerEventData eventData)
  22.     {
  23.         button.transform.localScale *= 1.5f;
  24.     }
  25.  
  26.     public void OnPointerExit(PointerEventData eventData)
  27.     {
  28.         button.transform.localScale /= 1.5f;
  29.     }
  30. }

猜你喜欢

转载自blog.csdn.net/u013509878/article/details/80158095