Unity基于EventSystem让SpriteRenderer支持点击事件

若2D场景中使用了UGUI的UI系统,则默认是有EventSystem的。否则可以创建个UGUI的物体,然后保留EventSystem,删除其它不需要的。

场景主相机添加Physics2DRaycaster组件,并妥善设置其EventMask属性。

为SpriteRenderer物体添加诸如BoxCollider2D等碰撞体组件,否则其接受不到射线检测。

下面扩展一个SpriteRendererButton组件,并添加到SpriteRenderer物体上:

csharp 复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;


public class SpriteRendererButtonClickEvent : UnityEvent
{
}

public class SpriteRendererButton : MonoBehaviour, IPointerClickHandler
{
    public bool enable = true;
    public SpriteRendererButtonClickEvent onClick = new SpriteRendererButtonClickEvent();

    public void OnPointerClick(PointerEventData eventData)
    {
        if (enable)
        {
            onClick?.Invoke();
        }
    }
}

后面的用法就和传统Button一样了!

同理3D项目中物体也可以使用类似的方式,使得3D物体可以使用我们熟悉的类似UGUI的点击事件。

相关推荐
weixin_4242946712 小时前
Unity的测试Edit Mode和Play Mode,有什么区别?
unity
Python私教16 小时前
我用 AI 做出了第一个 Godot 贪吃蛇
人工智能·游戏引擎·godot
玖玥拾16 小时前
Unity 3D 笔记(八)ScrollRect 滚动视图、NavMesh 自动寻路系统
笔记·3d·unity
淡海水2 天前
06-04-YooAsset源码-Unity加密解密服务
前端·unity·性能优化·c#·游戏引擎·yooasset
cd_949217212 天前
Unity游戏角色资产怎么快速制作?用V2Fun跑通生成、绑定和导入测试
游戏·unity·游戏引擎
HH‘HH2 天前
Unity 项目创建标准指南:分辨率、尺寸、文件路径与命名规范
unity·游戏引擎
元气少女小圆丶2 天前
unity发布web嵌入到前端页面的接受参数
前端·unity·webgl
HH‘HH2 天前
Unity 打包程序设置及注意事项全攻略
unity·游戏引擎
fqbqrr2 天前
2607d,parin游戏引擎
游戏引擎·d