Unity message sending mechanism parsing

Source: Internet
Author: User

The blog, only for analysis, analysis, analysis, has been sorted out, has been collated, has been collated well. Code core principle of the most popular on the internet, but also the most common game development applicable message mechanism. This in addition to some of their own optimization, great correction (haha), measured, no problem. In case of problems, welcome children's shoes can leave a message for me to amend.

Having kids shoes may be curious, unity does not have its own set of messages to send, such as what SendMessage, this ... This is almost impossible to use.

Why not use, look at the following is an online explanation, play demo or can use, but the actual development, is almost impossible to use.

I: It implements a pseudo-listener pattern, using a reflection mechanism.

The ii:sendmessage is inefficient because it iterates through the detection itself or the method to be called on the child node each time it is called.

III: Need to know the object in response to the event, also need a function name string of the response function as a parameter, if we have more than one object to respond to an event what to do, or we do not know which objects to respond to the event what to do. (the first two words are more abstract, this sentence can always read it)

1. ThinkingThe message sending mechanism can also be called the Observer design pattern (this should be the case).

It is easy to understand that an object sends a message, another, or several objects can receive the message at the same time and make their own different behavior (feedback, processing).

So, first of all, we think, what do we need?

I: What we need is the message (instance), the sender. Message (instance) + Sender = The message we need will be able to process any message.

II: How to send this message (Message Processing center).

III: The behavior of the sender sending (distributing) messages

IV: Receive messages.

Graphic:

  

2. Parsing1) Specific information

public class Notification {//<summary>///Sender///</summary> public gameobj        ECT sender;        <summary>///news content///</summary> public EventArgs param; <summary>///constructor (Initialize)///</summary>///<param name= "sender" > Notify sender// /<param name= "param" > Notification content public Notification (gameobject sender, EventArgs param) {this.se            NDEr = sender;        This.param = param; }
Public Notification () {}//<summary>//constructor////</summary>///& Lt;param name= "param" > Public Notification (EventArgs param) {this.sender = null; This.param = param; }}///<summary>////message, this is the message class specific message kind class////</summary> public class Eventargstest:eventargs { public int id; public string name; }
Notification is a slightly more abstract message class, to pass a message (class), I said before, it must be necessary to know the specific sender and the specific message class.
and the specific message class, is the back of the eventargstest, this is inherited from System.EventArgs, the class is a custom class, see behind, may understand why such inheritance.

 2) Declaring a delegate for a message

  

   public delegate void Onnotification (Notification notific);

  Declare a delegate to pass the above mentioned message class, which is a common point here: Declare a method that can pass the notification parameter. As for the usage of the delegate, there is an unspecified complaint.

3) Message Processing Center

   Public classNotificationcenter {Private StaticNotificationcenter instance =NULL;  Public StaticNotificationcenter Get () {if(Instance = =NULL) {instance=NewNotificationcenter (); returninstance; }            returninstance; }        Privatedictionary<UINT, notificationdelegate>eventlisteners=Newdictionary<UINT, notificationdelegate>();  Public voidAddEventListener (UINTEventkey, Notificationdelegate Listener) {            if(!Haseventlistener (Eventkey)) {Notificationdelegate del=NULL;//Defining MethodsEventlisteners[eventkey] = del;//Assigning a value to a delegate variable} Eventlisteners[eventkey]+ = listener;//monitoring of registered receivers        }         Public voidRemoveEventListener (UINTEventkey,notificationdelegate Listener) {            if(!Haseventlistener (eventkey))return; Eventlisteners[eventkey]-=Listener; if(Eventlisteners[eventkey] = =NULL) {RemoveEventListener (Eventkey); }        }         Public voidRemoveEventListener (UINTEventkey)        {Eventlisteners.remove (Eventkey); }        /// <summary>        ///Distributing events without needing to know the sender's situation/// </summary>        /// <param name= "Eventkey" ></param>        /// <param name= "notific" ></param>         Public voidPostdispatchevent (UINTEventkey, Notification notific) {            if(!Haseventlistener (eventkey))return; //Eventlisteners[eventkey]. Invoke (notific);Eventlisteners[eventkey] (notific); }        /// <summary>        ///distribution events, need to know the sender, the situation of the specific message/// </summary>        ///<param name= "Eventkey" >Event Key///<param name= "Sender" >sent by///<param name= "param" >Notification Content         Public voidPostdispatchevent (UINTEventkey, gameobject sender, EventArgs param) {            if(!Haseventlistener (eventkey))return; Eventlisteners[eventkey] (NewNotification (sender, param)); }         Public voidPostdispatchevent (UINTEventkey) {            if(!Haseventlistener (eventkey))return; Eventlisteners[eventkey] (NewNotification ()); }        /// <summary>        ///distribution events, do not need to know anything, just need to know sent over the message/// </summary>        ///<param name= "Eventkey" >Event Key///<param name= "param" >Notification Content         Public voidPostdispatchevent (UINTEventkey, EventArgs param) {            if(!Haseventlistener (eventkey))return; Eventlisteners[eventkey] (NewNotification (param)); }        /// <summary>        ///whether there is a listener for the specified event/// </summary>         Public BOOLHaseventlistener (UINTEventkey) {            returnEventlisteners.containskey (Eventkey); }    }

at the heart of the message mechanism, the difficulty is here.

first of all, since it is the message Processing center, it must be a storage passing the message (the delegate of the declaration above) container, then declare a

    Private dictionary<uint, onnotification> eventlisteners            new dictionary<UINT , onnotification> ();
Add, remove passing the message (the delegate of the declaration above) , is not the following code, it is important to note that
   Eventlisteners[eventkey]-= listener; // Cancel Listener       for receiver Eventlisteners.remove (Eventkey); // Remove the delivery message stored in eventlisteners for Eventkey (the delegate above)
    if (! Haseventlistener (eventkey))     {         // Register receiver's listener      }     else     {        // registered receiver of the listener, this usage, is commissioned a mechanism, do not understand their own to Baidu to see the commission.      }
This way, how to store the message is done.

4) The behavior of the sender sending (distributing) messages

/// <summary>    /// message type, enumeration listed, required to be strongly converted to    uint when invoked /// </summary>     Public enum // The enumeration value sent by the message should be converted to a UINT type     {        0,//test
1 , }

The above code, write enumeration, pure is to improve the readability and maintainability of code, C # to write more enumerations, less the inexplicable int variable, really thank the first company for my influence, to maintain good code readability.

   New eventargstest ();         3 ;         " I am the name message sent by test! " ;        Notificationcenter.get (). Postdispatchevent (uint) enotificationmsgtype.enull, args);      // // I am the notice, do not send specific what message, also can be Oh     

here to understand is postdispatchevent, this method, this way I wrote three heavy load, because send messages in three kinds of situations, such as comments

{

Just send notifications, do not need to know the specific message type to send, and do not need the sender.

Only the specific message type needs to be sent, not the sender.

A specific message type needs to be sent, which is required by the sender.

}

5) Receive messages

     voidAwake () {Notificationcenter.get (). AddEventListener ((UINT) Enotificationmsgtype.enull, updatetest); }    voidOnDestroy () {notificationcenter.get (). RemoveEventListener ((UINT) Enotificationmsgtype.enull, updatetest); }    voidupdatetest (Notification e) {eventargstest args= E.param aseventargstest; if(Args! =NULL)        {            stringStrName =Args.name; intStrid =args.id; }    }

you may be wondering why registering events and removing events are written in this way. This is a standard notation.

Write the initial (Start), End (OnDestroy), so that each message has its own life cycle.

 Updatetest has made its own behavior for receiving messages, noting that the passed parameters, of course, are message classes.


3. Summary

 
 Look at the diagram first and then read the code. If you do not understand, maybe the delegation is not understand very clearly, go to see the Commission, fully understand the Commission and then see this post promotion.
As a programmer who has been only doing hand-tours, the messaging mechanism is really fundamental to every game project.


Unity message sending mechanism parsing

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.