At the start of the project I brainstormed how objects and various components would communicate with each other. Researching online one finds a number of message passing systems. I wanted something slim to fit the small scope of my game. I found a design, I thought fairly useful, by Matthew Wegner on his Blurst Technology website. Reference provided below.
It works by instantiating a singleton instance of the Communicator component. All other components make use of the Communicator's function RegisterListener, to assign a listener for a given message type. A function to call when this message type is received.
Modifications
A number of modifications have been made to the original script. First, It is rewritten in C#, a superficial change. Second, more importantly, it does not use the Component.SendMessage function. There are debates on forums about the performance impact of this function, mainly because it uses reflection. Whether this is true or not I don't know with any certainty. I decided to avoid the function altogether since I planned on using this system in future projects. Instead I use 'events' and 'delegates' to call the appropriate function when a message is received. To transmit data a different types of message classes must be created. More on that below. Lastly, one can block and unblock certain types of messages from being transmitted to there destination. I found this to be occasionally useful.
Message Class And MessageType
Message class is the base class of all messages. Since one cannot anticipate what concrete messages will be created, the Communicator transmits all messages in the form of the base class. The message is then cast into it's concrete class, if necessary, when it is received by the receiver. The base class has one attribute which represents the type of message it is. For the base class it is of MessageType.Message. Every new type of message created must to be added to the MessageType Enum.
Say for example we have a MessageType to indicate a level start. Since we need to pass extra information to the receiver we create a new class to represent this type of message and subclass to that of Message. The constructor sets what type of message this is.
MessageType = MessageType.LEVEL_START;
How Broadcasting Works
How To Use The Communicator/Message classes
The following code demonstrates how to use the message and communicator classes. Being a trivial example, both functions called are in the same script. However, this does not have to be the case, and most likely would not be, since it is useless for the calling script to call its own functions via the Communicator. To run this example, attach the Driver script to a gameobject and run the scene.
The Communicator
This is the current version of the Communicator class used in the Cube Logic demo.
References
Original messaging system design found at: