先来看下效果图,图中点击 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 ())
{
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 OnClickHandler(UEvent uEvent)
{
this.targetAngle = this.targetAngle == 90f ? 0f : 90f; this.StopCoroutine (this.RotationOperater ());
this.StartCoroutine (this.RotationOperater());
} IEnumerator RotationOperater()
{
while (this.angle != this.targetAngle)
{
this.angle = Mathf.SmoothDampAngle (this.angle, this.targetAngle, ref currentVelocity, 0.5f);
this.transform.rotation = Quaternion.AngleAxis(this.angle, Vector3.forward); if(Mathf.Abs(this.angle - this.targetAngle) <= ) this.angle = this.targetAngle; yield return null;
}
}
}

Demo 事件侦听者(EventListener)SphereObject.cs,挂载在 Sphere 对象上

using UnityEngine;
using System.Collections; public class SphereObject : MonoBehaviour
{
private float position;
private float targetPosition;
private float currentVelocity; void Awake()
{
// 添加事件侦听
ObjectEventDispatcher.dispatcher.addEventListener (EventTypeName.CUBE_CLICK, OnClickHandler);
} /// <summary>
/// 事件回调函数
/// </summary>
/// <param name="uEvent">U event.</param>
private void OnClickHandler(UEvent uEvent)
{
this.targetPosition = this.targetPosition == 2f ? -2f : 2f; this.StopCoroutine (this.PositionOperater ());
this.StartCoroutine (this.PositionOperater());
} IEnumerator PositionOperater()
{
while (this.position != this.targetPosition)
{
this.position = Mathf.SmoothDamp (this.position, this.targetPosition, ref currentVelocity, 0.5f);
this.transform.localPosition = new Vector3(this.transform.localPosition.x, this.position, this.transform.localPosition.z); if(Mathf.Abs(this.position - this.targetPosition) <= 0.1f) this.position = this.targetPosition; yield return null;
}
}
}

Demo 辅助类 EventTypeName.cs

using UnityEngine;
using System.Collections; public class EventTypeName
{
public const string CUBE_CLICK = "cube_click";
}

Demo 辅助类 ObjectEventDispatcher.cs

using UnityEngine;
using System.Collections; public class ObjectEventDispatcher
{
public static readonly UEventDispatcher dispatcher = new UEventDispatcher();
}

事件触发器 UEventDispatcher.cs

using System;
using System.Collections.Generic; public class UEventDispatcher
{
protected Dictionary<string, UEventListener> eventListenerDict; public UEventDispatcher()
{
this.eventListenerDict = new Dictionary<string, UEventListener>();
} /// <summary>
/// 侦听事件
/// </summary>
/// <param name="eventType">事件类别</param>
/// <param name="callback">回调函数</param>
public void addEventListener(string eventType, UEventListener.EventListenerDelegate callback)
{
if (!this.eventListenerDict.ContainsKey(eventType))
{
this.eventListenerDict.Add(eventType, new UEventListener());
}
this.eventListenerDict[eventType].OnEvent += callback;
} /// <summary>
/// 移除事件
/// </summary>
/// <param name="eventType">事件类别</param>
/// <param name="callback">回调函数</param>
public void removeEventListener(string eventType, UEventListener.EventListenerDelegate callback)
{
if (this.eventListenerDict.ContainsKey(eventType))
{
this.eventListenerDict[eventType].OnEvent -= callback;
}
} /// <summary>
/// 发送事件
/// </summary>
/// <param name="evt">Evt.</param>
/// <param name="gameObject">Game object.</param>
public void dispatchEvent(UEvent evt, object gameObject)
{
UEventListener eventListener = eventListenerDict[evt.eventType];
if (eventListener == null) return; evt.target = gameObject;
eventListener.Excute(evt);
} /// <summary>
/// 是否存在事件
/// </summary>
/// <returns><c>true</c>, if listener was hased, <c>false</c> otherwise.</returns>
/// <param name="eventType">Event type.</param>
public bool hasListener(string eventType)
{
return this.eventListenerDict.ContainsKey(eventType);
}
}

事件侦听器 UEventListener.cs

using System;

public class UEventListener
{
public UEventListener() { } public delegate void EventListenerDelegate(UEvent evt);
public event EventListenerDelegate OnEvent; public void Excute(UEvent evt)
{
if (OnEvent != null)
{
this.OnEvent(evt);
}
}
}

事件参数 UEvent.cs

using System;

public class UEvent
{
/// <summary>
/// 事件类别
/// </summary>
public string eventType; /// <summary>
/// 参数
/// </summary>
public object eventParams; /// <summary>
/// 事件抛出者
/// </summary>
public object target; public UEvent(string eventType, object eventParams = null)
{
this.eventType = eventType;
this.eventParams = eventParams;
}
}

Unity3D 自定义事件(事件侦听与事件触发)的更多相关文章

  1. nodejs事件的监听与事件的触发

    nodejs事件(Events) 一.事件机制的实现 Node.js中大部分的模块,都继承自Event模块(http://nodejs.org/docs/latest/api/events.html  ...

  2. 浏览器标签tab窗口切换时事件状态侦听

    做到 是大屏项目,用的websocket,在浏览器切换标签窗口后,过了一段时间回来,页面会非常卡,所以想页面切回来的时候刷新页面,找到了这个方法,这是原来的例子.这段代码可以自己复制去做下测试 var ...

  3. vue02 过滤器、计算和侦听属性、vue对象的生命周期、阻止事件冒泡和刷新页面

    3. Vue对象提供的属性功能 3.1 过滤器 过滤器,就是vue允许开发者自定义的文本格式化函数,可以使用在两个地方:输出内容和操作数据中. 定义过滤器的方式有两种. 3.1.1 使用Vue.fil ...

  4. Spring Boot(六)自定义事件及监听

    事件及监听并不是SpringBoot的新功能,Spring框架早已提供了完善的事件监听机制,在Spring框架中实现事件监听的流程如下: 自定义事件,继承org.springframework.con ...

  5. Laravel 事件侦听的几个方法 [Trait, Model boot(), Observer Class]

    1 Trait 1.1 可以在 Trait 中定义一个静态的 bootFooBar() 方法,注:FooBar 是你的 Trait 名称 namespace App\Traits; use App\A ...

  6. 052_末晨曦Vue技术_处理边界情况之程序化的事件侦听器

    程序化的事件侦听器 点击打开视频讲解更详细 现在,你已经知道了 $emit 的用法,它可以被 v-on 侦听,但是 Vue 实例同时在其事件接口中提供了其它的方法.我们可以: 通过 $on(event ...

  7. EditText 监听回车事件 避免2次触发

    // 侦听回车事件 EidtText txtSN = (EditText) findViewById(R.id.txtSN); txtSN.setOnEditorActionListener(new ...

  8. WPF事件(一)内置路由事件

    原文:WPF事件(一)内置路由事件 Windows是消息驱动的操作系统,运行其上的程序也遵照这个机制运行,随着面向对象开发平台日趋成熟,微软把消息机制封装成了更容易让人理解的事件模型,一个事件包含3个 ...

  9. 异形Modbus客户端 和 异形modbus服务器之间的通讯 侦听模式的modbus-tcp客户端通讯

    前言 本文将使用一个Github公开的组件技术来实现一个异形ModBus TCP的客户端,方便的对异形Modbus tcp的服务器进行读写,这个服务器可以是电脑端C#设计的,也可以是特殊设备实现的,也 ...

随机推荐

  1. [Search Engine] 搜索引擎技术之查询处理

    我们之前从开发者的角度谈了一些有关搜索引擎的技术,其实对于用户来说,我们不需要知道网络爬虫到底是怎样爬取网页的,也不需要知道倒排索引是什么,我们只需要输入我们的查询词query,然后能够得到我们想要的 ...

  2. POJ 2478 Farey Sequence

     名字是法雷数列其实是欧拉phi函数              Farey Sequence Time Limit: 1000MS   Memory Limit: 65536K Total Submi ...

  3. single-table inheritance 单表继承

    type 字段在 Rails 中默认使用来做 STI(single-table inheritance),当 type 作为普通字段来使用时,可以把SIT的列设置成别的列名(比如不存在的某个列). 文 ...

  4. Spring @AspectJ 实现AOP 入门例子(转)

    AOP的作用这里就不再作说明了,下面开始讲解一个很简单的入门级例子. 引用一个猴子偷桃,守护者守护果园抓住猴子的小情节. 1.猴子偷桃类(普通类): package com.samter.common ...

  5. Andorid实现点击获取验证码倒计时效果

    这篇文章主要介绍了Andorid实现点击获取验证码倒计时效果,这种效果大家经常遇到,想知道如何实现的,请阅读本文   我们在开发中经常用到倒计时的功能,比如发送验证码后,倒计时60s再进行验证码的获取 ...

  6. FreeRTOS学习及移植笔记之一:开始FreeRTOS之旅

    1.必要的准备工作 工欲善其事,必先利其器,在开始学习和移植之前,相应的准备工作必不可少.所以在开始我们写要准备如下: 测试环境:我准备在STM32F103平台上移植和测试FreeRTOS系统 准备F ...

  7. 19. Remove Nth Node From End of List

    题目: Given a linked list, remove the nth node from the end of list and return its head. For example, ...

  8. 安装学习nginx记录

    通过查看nginx目录下的log文件,发现80端口没有权限使用 查找文章发现: netstat -aon|findstr ":80" 有的进程ID占用多了80端口,看监听的端口 启 ...

  9. intellij idea 插件 ideaVim 用法

    intellij idea 插件 ideaVim - Genji_ - 博客园http://www.cnblogs.com/nova-/p/3535636.html IdeaVim插件使用技巧 - - ...

  10. 对DIP IoC DI的理解与运用

    DIP,IoC,DI基本概念 依赖倒置原则(DIP,Dependency Inverse Principle):强调系统的“高层组件”不应当依赖于“底层组件”,并且不论是“高层组件”还是“底层组件”都 ...