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. HTML DOM 节点介绍(nodeName,nodeValue,nodeType)

    对于初学者来说,HTML DOM 里面的 nodeName.nodeValue 以及 nodeType 三个属性的作用和取值不是很清楚.下面整理的信息包含有关于节点的详细信息,供参考. 节点信息 每个 ...

  2. CSS浏览器兼容问题集-第二部分

    11.高度不适应 高度不适应是当内层对象的高度发生变化时外层高度不能自动进行调节,特别是当内层对象使用margin 或paddign 时.   例:  #box {background-color:# ...

  3. 【洛谷P1104】生日

    题目描述 cjf君想调查学校OI组每个同学的生日,并按照从大到小的顺序排序.但cjf君最近作业很多,没有时间,所以请你帮她排序. 输入输出格式 输入格式: 有2行,第1行为OI组总人数n:第2行至第n ...

  4. Linux下命令lrzsz

    lrzsz是什么 在使用Linux的过程中,难免少不了需要上传下载文件,比如往服务器上传一些war包之类的,之前都是使用winSCP,lrzsz是一个更方便的命令,可以直接在Linux中输入命令,弹出 ...

  5. 避免无用的渲染绘制(Avoiding Unnecessary Paints)

    本文翻译自html5rock上的文章,文章英文原版地址在最后给出. 文中的Paints我翻译成渲染绘制,我自己是这么理解. 开始 绘制(渲染)一个网站或者一个应用的元素对浏览器来说开销是很大的,它会对 ...

  6. 设计模式之Proxy

    设计模式总共有23种模式这仅仅是为了一个目的:解耦+解耦+解耦...(高内聚低耦合满足开闭原则) 为什么要使用Proxy? 1.授权机制 不同级别的用户对同一对象拥有不同的访问权利. 2.某个客户端不 ...

  7. DataFrame衍生新特征操作

    1.DataFrame中某一列的值衍生为新的特征 #将LBL1特征的值衍生为one-hot形式的新特征 piao=df_train_log.LBL1.value_counts().index #先构造 ...

  8. 日常开发技巧:x11-forward,使用远程机器的gui程序

    背景 日常用过ssh登录服务器进行工作,尽管大部分时间,都只需要终端操作,编辑源码也是vim就够用了. 但有时候,还是需要使用gui程序的,比如打开一份pdf,word,ppt,excel等. 碰到这 ...

  9. 【转载】C#异常Retry通用类

    //Retry机制 public static class Retry { /// <summary> /// 重试零个参数无返回值的方法 /// </summary> /// ...

  10. BZOJ 1975: [Sdoi2010]魔法猪学院——K短路,A*

    传送门 http://www.lydsy.com/JudgeOnline/problem.php?id=1975 题意&简要做法 一张有向图,求出最多的互不相同的路径,满足路径长度之和\(\l ...