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. div 画table尝试

    .left { float: left; } .table { border: solid 1px black; width: 750px; } .tr { width: 100%; height: ...

  2. 深入浅出CSS(二):关于雪碧图、background-position与steps函数的三角恋情

    [测试代码] HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset=&qu ...

  3. 分块+二分,统计对数 CDOJ

    http://acm.uestc.edu.cn/#/problem/show/1157 数列(seq) Time Limit: 3000/1000MS (Java/Others)     Memory ...

  4. 无聊,纯css写了个评分鼠标移入的效果

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  5. Java读取大文件的高效率实现

    1.概述 本教程将演示如何用Java高效地读取大文件.这篇文章是Baeldung (http://www.baeldung.com/) 上“Java——回归基础”系列教程的一部分. 2.在内存中读取 ...

  6. python 版本zabbix_sender

    python版本的zabbix_sender: 使用方法:    1.导入 : from zbx_send import info        2.实例化: test=info()     3.支持 ...

  7. Ubuntu 下 CodeBlocks 修改用户自定义颜色主题 及 更新CodeBlocks到最新版本

    Code::Blocks默认的白色编辑器界面看久了眼睛很累, 所以想换成dark的主题, 眼睛会舒服些. 1. 安装好codeblocks后, 先运行一次, 关闭, 这时程序会提示你是否要保存defa ...

  8. 遍历目录大小——php经典实例

    遍历目录大小——php经典实例 <?php function dirSize($dir){ //定义大小初始值 $sum=; //打开 $dd=opendir($dir); //遍历 while ...

  9. NASA: A Closer View of the Moon(近距离观察月球)

    Posted to Twitter by @Astro_Alex, European Space Agency astronaut Alexander Gerst, this image shows ...

  10. Windows降权

    使用invoke-tokenmanipulation进行降权 枚举所有令牌 PS C:\Users\SMC> Get-ExecutionPolicy Restricted PS C:\Users ...