Building robust and flexible Event System in Unity3d

Source: Internet
Author: User

Building robust and flexible Event System in unity3d1. Prerequisites1.1 Observer Pattern

According to Wikipedia, the Observer pattern was a software design pattern in which an object, called the subj ECT, maintains a list of its dependents, called observers, and notifies them automatically of any State Chan GES, 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 on 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 F Ound, ...).

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 an D Potential trouble in implementing it.

1.2.1 The delegateKeyword

delegateis a special the data type in C # representing functions. It's similar to function pointer in C, but have the advantage of multicasting, which allows combining different fu Nctions to 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 eventKeyword

eventThe data type is just similar delegate to the data type, but it doesn ' t allow any modification other than adding and re Moving 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 are that a function must being removed from the event variable if the object it belongs to have be En disabled or garbage collected, otherwise erroneous behaviors may occur.

2. Example Usage

Suppose we have a boss in game so 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 Bossslaughter    Edaction ();    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 ("Hunting legendary prey, game over!")        ", 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.