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");
    }
}

原文地址:https://www.cnblogs.com/hehao98/p/9244912.html

时间: 2024-11-24 15:09:39

Building Robust and Flexible Event System in Unity3D的相关文章

2-5 事件系统(Event System)

重点 1.对于用户操作的事件,是由事件系统控制的 2.事件系统的动作是通过输入模块定义的 3.对于那个对象发生事件,由光线投射判定. 2-3-1 事件系统概要事件系统通过场景中的“Event System”对象所附加的组件发挥功能 Standalone Input Module(独立输入模块)组件是具有通过鼠标,键盘和游戏控制杆输入功能Touch Input Module(触摸输入模块)组件是具有智能手机和平板电脑等移动设备上触碰功能 现在2018.3.9f1版本中,Touch Input Mo

UICamera(NGUI Event system)原理

看了UICamera的源码就显而易见了: UICamera « on: November 21, 2013, 12:21:48 AM » Overview UICamera is a somewhat poorly named component. In fact, its name is kept only for backwards compatibility purposes. What the UICamera script actually does is sends out NGUI

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 consisting of a solid grounding in the object-oriented (OO) approach and implementing the best OO practices heavily laced with how to sidestep the OO pitfal

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

以前研究过eclipse +ADT开发android app,没深入再加上工作也用不上就扔在那,现在需要做APP开发,发现eclipse +ADT也不再更新了,google推出了功能强大的Android Studio,最新版本都到了2.1正式版,搜索了一下网上的教程,基本上都是以前版本的,虽然变化不大,但有些地方还是模不着头脑,现将学习过程记载如下,一是备忘,二是有同好可以参考 一.Android Studio 2.1新特性介绍 Android Studio 是一个全新的 Android 开发环

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

目录 1. 为什么要构建日志系统 2. 通用日志系统的总体架构 3. 日志系统的元数据来源:data source 4. 日志系统的子安全域日志收集系统:client Agent 5. 日志系统的中心日志整合系统:log server 6. 日志系统的后端存储系统:log DB 7. 日志系统搭建学习 1. 为什么要构建日志系统 log是管理员每日需要查看的文件记录.里面记载了大量系统正常和不正常的运行信息,这些信息对管理员分析系统的状况.监视系统的活动.发现系统入侵行为是一个相当重要的部分对于

Single-stack real-time operating system for embedded systems

A real time operating system (RTOS) for embedded controllers having limited memory includes a continuations library, a wide range of macros that hide continuation point management, nested blocking functions, and a communications stack. The RTOS execu

暴风魔镜SDK在Unity3D 5.6中的简单应用

去年买了个暴风魔镜4,如今一直放在家里吃灰,这些天对Unity3D开发VR兴趣正浓,刚好公司项目不忙,花了几天玩玩暴风魔镜SDK,因为网上的资料不算多,暴风提供的文档也不太适合像我这样的Unity小白,所以爬了好久坑终于可以在手机上运行了. 运行效果图: 开发环境: 开发工具:Unity 5.6 暴风魔镜SDK:MojingSDK For Unity V1.3.5112 (R).zip SDK更新时间:2017.03.14 简单记录下Unity3D 5.6步骤: 创建一个Unity3D工程,解压

unity3d游戏无法部署到windows phone8手机上的解决方法

今天搞了个unity3d游戏,准备部署到自己的lumia 920上,数据线连接正常,操作正常,但是"build"以后,始终无法部署到手机上,也没有在选择的目录下生产任何相关文件. 但是提示有一个错误: Error building Player: Exception: Error: method `System.Byte[] System.IO.File::ReadAllBytes(System.String)` doesn't exist in target framework. I

[Unity3D]事半功倍:界面插件NGUI的使用教程与实例

[Unity3D]事半功倍:界面插件NGUI的使用教程与实例 原文地址:http://www.tasharen.com/?page_id=185 NGUI下载地址:点我传送 NGUI教程:步骤1-Scene 1.创建一个新的场景(New Scene).2.选择并删除场景里的MainCamera.3.在NGUI菜单下选择Create a New UI,会打开UI创建向导. 4.在创建向导中你能更改UI的基本参数.现在我们选Default layer,点击Create Your UI 按钮.5.就这