三维物体常用的交互事件有点击、拖拽等。将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);
}
}
其他事件也是相同的方法使用。