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的更多相关文章

  1. The Event System

    The Event System 在Qt中,事件是继承了虚拟类QEvent的对象,它代表了程序所发生的事情或者程序需要知道的一个外部活动的结果.事件可以被任意 QObject子类的实例接收和处理,是与 ...

  2. 【SaltStack官方版】—— Events&Reactor系统—EVENT SYSTEM

    Events&Reactor系统 EVENT SYSTEM The Salt Event System is used to fire off events enabling third pa ...

  3. event system

    事件的概念 简单来说, 就是应用程序感兴趣的应用内部或者外部的活动结果. 在Qt中, 使用QEvent 抽象这些活动. 事件驱动模型 事件驱动模型现在在计算机很多领域都有使用. 例如 BSD sock ...

  4. UICamera(NGUI Event system)原理

    看了UICamera的源码就显而易见了: UICamera « on: November 21, 2013, 12:21:48 AM »   Overview UICamera is a somewh ...

  5. [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 ...

  6. 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 ...

  7. Android入门:一、Android Studio 2.1安装及初始化配置

    以前研究过eclipse +ADT开发android app,没深入再加上工作也用不上就扔在那,现在需要做APP开发,发现eclipse +ADT也不再更新了,google推出了功能强大的Androi ...

  8. Linux System Log Collection、Log Integration、Log Analysis System Building Learning

    目录 . 为什么要构建日志系统 . 通用日志系统的总体架构 . 日志系统的元数据来源:data source . 日志系统的子安全域日志收集系统:client Agent . 日志系统的中心日志整合系 ...

  9. Single-stack real-time operating system for embedded systems

    A real time operating system (RTOS) for embedded controllers having limited memory includes a contin ...

随机推荐

  1. UVA 1575 Factors

    https://vjudge.net/problem/UVA-1575 题意: 令f(k)=n 表示 有n种方式,可以把正整数k表示成几个数的乘积的形式. 例 10=2*5=5*2,所以f(10)=2 ...

  2. 算法专题-STL篇

    这篇文章着重记录c++中STL的用法.主要粗略的介绍其用法,以知识点的形式呈现其功能,不会深入源码分析其工作原理. 排序和检索. sort(a,a+n),对a[0]往后的n个元素(包括a[0])进行排 ...

  3. 其他:strtok和sscanf结合输入读取一行整数

    gets(buf); int v; char *p = strtok(buf," "); while(p) { sscanf(p,"%d",&v); p ...

  4. GridControl GridView 修改表格中的标题居中

    Grid Designer>Views>Appearance>HeaderPanel>TextOptions>HAIignment{Center} 依次打开并找到HAIL ...

  5. 【BZOJ】4555: [Tjoi2016&Heoi2016]求和 排列组合+多项式求逆 或 斯特林数+NTT

    [题意]给定n,求Σi=0~nΣj=1~i s(i,j)*2^j*j!,n<=10^5. [算法]生成函数+排列组合+多项式求逆 [题解]参考: [BZOJ4555][Tjoi2016& ...

  6. 【CodeForces】708 C. Centroids 树的重心

    [题目]C. Centroids [题意]给定一棵树,求每个点能否通过 [ 移动一条边使之仍为树 ] 这一操作成为树的重心.n<=4*10^5. [算法]树的重心 [题解]若树存在双重心,则对于 ...

  7. Spring Boot中使用Spring Security进行安全控制

    我们在编写Web应用时,经常需要对页面做一些安全控制,比如:对于没有访问权限的用户需要转到登录表单页面.要实现访问控制的方法多种多样,可以通过Aop.拦截器实现,也可以通过框架实现(如:Apache ...

  8. thinkphp 漂亮的分页样式

    ---恢复内容开始--- 首先:需要两个文件 page.class.php page.css 1.在TP原有的 page.class.php 文件稍作修改几条代码就可以了, 修改过的地方我会注释, 2 ...

  9. PyCharm 自定义文件和代码模板

    PyCharm提供了文件和代码模板功能,可以利用此模板来快捷新建代码或文件.比如在PyCharm中新建一个html文件,新的文件并不是空的,而是会自动填充了一些基础的必备的内容,就像这样: <! ...

  10. 74.VS2013和opencv3.1.0安装教程

    一.先下载文件 1.VS2013 VS2013有很多版本,专业版,旗舰版,中文英文之类的,所对应的密钥也不一样.我选择的是简体中文专业版.下载链接如下. http://www.musnow.com/t ...