Building Robust and Flexible Event System in Unity3D
Building Robust and Flexible Event System in Unity3D
1. Prerequisites
1.1 Observer Pattern
According to Wikipedia, the observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. (I omitted the definition in the Gang of Four book since it's not easy to understand)
Observer Pattern is often used in game when you need to build a event system. A event system is capable of notifying other classes about some specific events (player died, boss slaughtered, key item found, ...).
1.2 Observer Pattern in C# Language
Observer pattern is so commonly used that C# supports observer pattern at language level, which saves us a lot of labor and potential trouble in implementing it.
1.2.1 The delegate keyword
delegate is a special data type in C# representing functions. It's similar to function pointer in C, but has the advantage of multicasting, which allows combining different functions into a single variable.
delegate void MyDelegate(int num);
public void UseDelegate() {
    MyDelegate myDelegate = f;
    myDelegate += g;
    myDelegate();
}
public void f(int a) {...}
public void g(int b) {...}
1.2.2 The event keyword
The event data type is just similar to the delegate data type, but it doesn't allow any modification other than adding and removing observers to/from the event variable.
public delegate void ClickAction();
public static event ClickAction OnClicked;
OnClicked += button1.ProcessClicked;
OnClicked += scene.ProcessClicked;
OnClicked -= button1.ProcessClicked;
OnClicked -= scene.ProcessClicked;
An important thing to notice is that a function MUST be removed from the event variable if the object it belongs to has been disabled or garbage collected, otherwise erroneous behaviors may occur.
2. Example Usage
Suppose we have a boss in game that we can slaughter it to win the level. When the boss died three class need to response to it. The player should cheer, the UI should display message and the game should end a few seconds later. Then we can arrange our code as follows:
public class GameManager : MonoBehaviour {
	// Manage Events
	public delegate void BossSlaughteredAction();
	public static event BossSlaughteredAction bossSlaugheredAction;
	public static void OnBossSlaughtered() {
		if (bossSlaugheredAction != null) bossSlaugheredAction();
	}
	void OnEnable() {
		bossSlaugheredAction += HandleBossSlaughtered;
	}
	void OnDisable() {
		bossSlaugheredAction -= HandleBossSlaughtered;
	}
	public void HandleBossSlaughtered() {
		//Debug.Log("Boss Slaughtered!");
		DisplayTextAtScreen("猎得传奇猎物,游戏结束!", 5.0f);
		Invoke("ProcessGameEnding", 5.0f);
	}
    void ProcessGameEnding() {
		UnityEngine.SceneManagement.SceneManager.LoadScene("StartMenu");
	}
}
public class BeerAttributes : MonoBehaviour {
	[SerializeField] float health = 100.0f;
	void TakeDamage(float amount) {
		health -= amount;
		if (health <= 0) {
			this.enabled = false;
			//Debug.Log("Die");
			GameManager.OnBossSlaughtered();
		}
	}
}
public class WolfEventHandler : MonoBehaviour {
	void OnEnable() {
		GameManager.bossSlaugheredAction += HandleBossSlaughtered;
	}
	void OnDisable() {
		GameManager.bossSlaugheredAction -= HandleBossSlaughtered;
	}
	void HandleBossSlaughtered() {
		Animator animator = GetComponent<Animator>();
		animator.SetTrigger("Cheer");
	}
}
												
											Building Robust and Flexible Event System in Unity3D的更多相关文章
- The Event System
		
The Event System 在Qt中,事件是继承了虚拟类QEvent的对象,它代表了程序所发生的事情或者程序需要知道的一个外部活动的结果.事件可以被任意 QObject子类的实例接收和处理,是与 ...
 - 【SaltStack官方版】——  Events&Reactor系统—EVENT SYSTEM
		
Events&Reactor系统 EVENT SYSTEM The Salt Event System is used to fire off events enabling third pa ...
 - event system
		
事件的概念 简单来说, 就是应用程序感兴趣的应用内部或者外部的活动结果. 在Qt中, 使用QEvent 抽象这些活动. 事件驱动模型 事件驱动模型现在在计算机很多领域都有使用. 例如 BSD sock ...
 - UICamera(NGUI Event system)原理
		
看了UICamera的源码就显而易见了: UICamera « on: November 21, 2013, 12:21:48 AM » Overview UICamera is a somewh ...
 - [React] Normalize Events with Reacts Synthetic Event System
		
Event handlers are passed an instance of SyntheticEvent in React. In this video we'll take a look at ...
 - Three Sources of a Solid Object-Oriented Design
		
pingback :http://java.sys-con.com/node/84633?page=0,1 Object-oriented design is like an alloy consis ...
 - Android入门:一、Android Studio 2.1安装及初始化配置
		
以前研究过eclipse +ADT开发android app,没深入再加上工作也用不上就扔在那,现在需要做APP开发,发现eclipse +ADT也不再更新了,google推出了功能强大的Androi ...
 - Linux System Log Collection、Log Integration、Log Analysis System Building Learning
		
目录 . 为什么要构建日志系统 . 通用日志系统的总体架构 . 日志系统的元数据来源:data source . 日志系统的子安全域日志收集系统:client Agent . 日志系统的中心日志整合系 ...
 - Single-stack real-time operating system for embedded systems
		
A real time operating system (RTOS) for embedded controllers having limited memory includes a contin ...
 
随机推荐
- Final类和Final方法
			
终止继承 Final类 当关键字final用来修饰类时,其含义是该类不能在派生子类.换句话说,任何其他类都不能继承用final修饰的类,即使该类的访问限制为public类型,也不能被继承:否则,将编译 ...
 - 庞老师集群.ziw
			
2017年2月17日, 星期五 庞老师集群 链接:http://pan.baidu.com/s/1mhSw2TE 密码:hzz4 更改子网IP,及网关: null
 - 【bzoj】2326 [HNOI2011]数学作业
			
[题意]给定n和m,求1~n从高位到低位连接%m的结果.n=11时,ans=1234567891011%m.n<=10^18,m<=10^9. [算法]递推+矩阵快速幂 [题解] 考虑枚举 ...
 - 【BZOJ】2038: [2009国家集训队]小Z的袜子(hose)
			
[题意]给定n个数字ai,每次询问一个区间中随机抽选两个数字,数字相同的概率,以分数最简形式输出.n,ai<=50000. [算法]莫队算法 [题解]参考:莫队……讲稿? by Foreseea ...
 - DIDM源码分析
			
DIDM源码分析 版本来源:GitHub上Opendaylight DIDM项目 参考资料来源:DIDM:Developer Guide 概述 DIDM是设备标识与驱动管理(Device Identi ...
 - 使用Burpsuite爆破弱口令教工号
			
使用Burpsuite爆破弱口令教工号 发表于 2015-11-18 | 分类于 Burpsuite | 1条评论 | 26次阅读 准备 所谓工欲善其事,必先利其器,首先当然是要下 ...
 - win10-idea2018
			
下载jar JetbrainsCrack-2.9-release-enc.jar idea64.exe.vmpotions 配置 -javaagent:D:\devsoft\idea\bin\Jetb ...
 - makefile使用.lds链接脚本以及 $@ ,$^, $,< 解析【转】
			
转自:http://www.cnblogs.com/lifexy/p/7089873.html 先来分析一个简单的.lds链接脚本 例1,假如现在有head.c init.c nand.c main. ...
 - windos8设置cpu数量和内存大小
			
转自:http://smilejay.com/2012/03/windows_cpu_memory_setting/ Windows 8(测试版)在作为Xen Guest中的benchmark测试.我 ...
 - Linux 上配置 NTP SERVER
			
在CENTOS 6.2上面安装配置NTP SERVER 安装NTP:yum install ntp 配置时间源vi /etc/ntp.confserver 210.72.145.44server nt ...