Using the event/delegation mechanism (event/delegate) in Unity for Gameobject

Source: Internet
Author: User



Welcome to Unity Learning,Unity training ,UnityEnterprise TrainingEducation Area, there are manyu3d Resources,u3d Training Video,u3d Tutorials,U3d Frequently Asked questions,u3d Project Source code, the "Dog Planing Learning Network" Unity's Ultimate Academy, dedicated to building the industry unity3d Training , learning the first brand.



  What are the drawbacks of a one-to-many observer pattern mechanism?
  
If you're not quite sure how to use the event/delegation mechanism in unity, we recommend that you review my previous article: "Unity3d tricks" Use the event/delegation mechanism (event/delegate) in unity for communication between Gameobject

in the previous blog, we wrote that "Unity3d technique" uses the event/delegation mechanism (event/delegate) in unity to communicate between Gameobject, which uses the EventHandler delegate as a common event type. Implements a one-to-many observer pattern. But what is the disadvantage of doing so? Let's take the example of a bird hitting a pipe as described above:
  

in this case, when the bird knocks down the pipe, the bird sends aCreate a collisionmessage to all observers, so if we add a new name to the Swan and it can fly in the sky, then we're going to implement a similar function within its class .Create a collisionmessage to all observers, resulting in code duplication, the software that solves the problem of code duplication is generally used to introduce the middle tier approach, So I wrote a ccnotificationcenter in the Cocos2d-x Ccnotificationcenter to store various messages and forward them as the middle tier.

  introduction of Middle Layer--notificationcenter

Notificationcenter basic design ideas are based on the MessageDispatcher model, even if a dictionary (Dictionary) to record the various information to be forwarded, as well as the observer of the information, Then the message is forwarded at the appropriate time. Notificationcenter should also provide a way for observers to subscribe and unsubscribe.
Notificationcenter is based on a single-piece pattern, which is initialized the first time the GetInstance method is called, and the reason for using a single piece is to make the life of notificationcenter longer than any observer, This will not occur if the notificationcenter is empty.
in the following code, the reason why I made inotificationcenter into an abstract class is that I want to create multiple subclasses by inheriting this class, such as the ability to create Uinotificationcenter, Battlenotificationcenter,tradenotificationcenter. To group the messages.
below I put my own code share, for everyone's reference:

Using Unityengine;
Using System;
Using System.Collections;
Using System.Collections.Generic;
Notificationcenter extension class, here to make a number of Inotificationcenter sub-class,
Handle different message forwarding separately to facilitate message grouping
public class Notificationcenter:inotificationcenter
{
private static Inotificationcenter Singleton;
Private event EventHandler Gameover;
Private event EventHandler Scoreadd;
Private Notificationcenter ()
: Base ()
{
Add the various messages you need to distribute here
Eventtable[gameover]
= Gameover;
Eventtable[scoreadd]
= Scoreadd;
}
public static Inotificationcenter getinstance ()
{
if (singleton = = null)
Singleton = new Notificationcenter ();
return singleton;
}
}
Abstract base class for Notificationcenter
Public abstract class Inotificationcenter
{
Protected dictionarystring, EventHandler eventtable;
Protected Inotificationcenter ()
{
eventtable = new dictionarystring, EventHandler ();
}
Postnotification--name is named, Sender is sender, message with parameter E is sent out
public void Postnotification (string name)
{
This. Postnotification (name, null, eventargs.empty);
}
public void Postnotification (string name, object sender)
{
This. Postnotification (name, name, Eventargs.empty);
}
public void Postnotification (string name, object sender, EventArgs e)
{
if (Eventtable[name]
! = NULL)
{
Eventtable[name] (sender, E);
}
}
Added or removed a callback function.
public void addEventHandler (string name, EventHandler handler)
{
Eventtable[name]
+ = handler;
}
public void removeEventHandler (string name, EventHandler handler)
{
Eventtable[name]
-= handler;
}
}

  abstraction of observers-introduction of observer
after joining Notificationcenter, the next problem we have to face is that each of our observers needs to add a callback function to our Start method and cancel the callback function in the OnDestroy method. We can abstract this part of the code in a observer component, using another dictionary to record all of the Gameobject registered callback functions, in the Observer OnDestroy method all at once unsubscribe. The code is as follows:
  
Using Unityengine;
Using System.Collections;
Using System.Collections.Generic;
Using System;
public class Observer:monobehaviour {
Private Inotificationcenter Center;
Private dictionarystring, EventHandler handlers;
void Awake () {
handlers = new dictionarystring, EventHandler ();
Center = notificationcenter.getinstance ();
}
void OnDestroy () {
foreach (keyvaluepairstring, EventHandler kvp in handlers) {
Center. removeEventHandler (KVP. Key, kvp. Value);
}
}
public void addEventHandler (string name, EventHandler handler) {
Center. addEventHandler (name, handler);
Handlers. ADD (name, handler);
}
}

For more information, please visit"Dog Planing Learning Network" Unity Ultimate Academy Http://edu.gopedu.com  
Disclaimer: This document is from"Dog Planing Learning Net"Community-Unity Ultimate Academy, is the Netizen self-published Unity3d study articles, if there is any content infringement of your relevant interests, please communicate with the official, we will deal with it immediately.

Using the event/delegation mechanism (event/delegate) in Unity for Gameobject

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.