Unity 委托方式实现鼠标对三维物体的交互事件

三维物体常用的交互事件有点击、拖拽等。将EventDispatcher脚本挂载到需要有交互功能的物体上,当需要开启交互功能时,将需要的交互事件注册(订阅)上即可实现交互功能。
EventDispatcher实现了一些简单的鼠标操作,代码如下:

using UnityEngine;
using System.Collections;


public class EventDispatcher : MonoBehaviour
{

    public delegate void EventHandler(GameObject e);

    public event EventHandler MouseDown;//鼠标按下
    public event EventHandler MouseDrag;//鼠标拖拽
    public event EventHandler MouseUp;//鼠标抬起
    public event EventHandler MouseOver;//鼠标悬停在物体上方时
    public event EventHandler MouseExit;//鼠标离开物体时

    void OnMouseDown()
    {

        if (MouseDown != null)

            MouseDown(this.gameObject);       

    }
    void OnMouseDrag()
    {

        if (MouseDrag != null)

            MouseDrag(this.gameObject);          
    }
    void OnMouseUp()
    {

        if (MouseUp != null)

            MouseUp(this.gameObject);        

    }
    void OnMouseOver()
    {

        if (MouseOver != null)

            MouseOver(this.gameObject);

    }
    void OnMouseExit()
    {

        if (MouseExit != null)

            MouseExit(this.gameObject);      
    }
}

使用示例:
1、在场景中创建一个Cube,将EventDispatcher脚本挂载到Cube物体上
2、创建脚本Test并将脚本挂载到场景物体中,在脚本注册点击事件,脚本如下:

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Test : MonoBehaviour {

    // Use this for initialization
    void Start() {

        GameObject clickObj = GameObject.Find("Cube");
        Debug.Log(clickObj);
        if (clickObj != null) {
            clickObj.GetComponent<EventDispatcher>().MouseDown += OnMouseDown;          
        }

      
	}
    private void OnMouseDown(GameObject e)
    {
        Debug.Log("点击物体:"+e);
    }

}

在这里插入图片描述
其他事件也是相同的方法使用。

  • 5
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值