先来看下效果图,图中点击 Cube(EventDispatcher),Sphere(EventListener)以及 Capsule(EventListener)会做出相应的变化,例子中的对象相互之间没有引用,也没有父子关系。
Demo 事件触发者(EventDispatcher)CubeObject.cs,挂载在 Cube 对象上
using UnityEngine; using System.Collections; public class CubeObject : MonoBehaviour { void Update() { if (Input.GetMouseButtonDown (0)) { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit raycastHit = new RaycastHit(); if(Physics.Raycast(ray, out raycastHit)) { if(raycastHit.collider.gameObject.name == "Cube") { // 触发事件 ObjectEventDispatcher.dispatcher.dispatchEvent(new UEvent(EventTypeName.CUBE_CLICK, "cube"), this); } } } } }
Demo 事件侦听者(EventListener)CapsuleObject.cs,挂载在 Capsule 对象上
using UnityEngine; using System.Collections; public class CapsuleObject : MonoBehaviour { private float angle; private float targetAngle; private float currentVelocity; void Awake() { // 添加事件侦听 ObjectEventDispatcher.dispatcher.addEventListener (EventTypeName.CUBE_CLICK, OnClickHandler); } /// <summary> /// 事件回调函数 /// </summary> /// <param name="uEvent">U event.</param> private void OnClickHandle