The code in this article is licensed CC0. Attribution is great, but you don’t have to.

Loose coupling is a goal drilled into every novice programmer when they’re learning the trade. If you have loose coupling among your classes, it reduces the changes you have to make to a class when you change a class on which it depends. A great way to move towards loose coupling is by abstracting away the dependency of one object on another using a Messenger.

Note: This tutorial is aimed towards Unity users, but the code and approaches are applicable to any system.

The Problem

You’re making the next great indie title. You’re a small team of two programmers and three artists, and you’ve been working on your game for a year. You have your functionality in place and it’s time to start polishing, but polishing takes a long time. It’s a lot of work, you’ve got model code mixed up with the view. Changing even the smallest thing means you have to follow 9 or 10 different references to other classes all over your game. Changing the high score manager means you have to change the high score rendering code, the high score server, the game’s score metric, and the list goes on. You’ve not been a bad developer though, you’re using events instead of polling, but it’s not enough. You want your classes to be more atomic, you want loose coupling.

The Solution

Enter the Messenger. The Messenger is a central hub, like a post office or router for distributing messages from sender to receiver. The sender doesn’t know who (or if anything) will receive their message, and the receiver has no knowledge of who sent it. The objects have loose coupling, but the receiver can still act on data and events from the sender. Importantly, this also means that if it becomes time to replace either the sender or the receiver, no code needs to change in the counterpart class. The sender will continue to send out their messages as they should, and the receiver will continue to act on them as they should.

This implementation of a Messenger is based on the Messenger API from Laurent Bugnion’s MVVM Lite framework, but with a few additions.

public class Health { public event EventHandler OnHurt; public int Life { get; set; } public Health() { Life = 0; } public void Hurt() { Life--; if(OnHurt != null) { OnHurt(this, EventArgs.Empty); } } } //Meanwhile in the view public class HealthLabel { public HealthLabel(Health health) { health.OnHurt += HealthHurtEventHandler; } private void HealthHurtEventHandler(object sender, EventArgs e) { Print((sender as Health).Life); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 public class Health { public event EventHandler OnHurt ; public int Life { get ; set ; } public Health ( ) { Life = 0 ; } public void Hurt ( ) { Life -- ; if ( OnHurt != null ) { OnHurt ( this , EventArgs . Empty ) ; } } } //Meanwhile in the view public class HealthLabel { public HealthLabel ( Health health ) { health . OnHurt += HealthHurtEventHandler ; } private void HealthHurtEventHandler ( object sender , EventArgs e ) { Print ( ( sender as Health ) . Life ) ; } }

In the above example, the player has a Health component attached to it, which when hit reduces the Life variable by 1. We also have a HealthLabel which renders the value in the attached Health component on screen. It does so by checking for the OnHurt event in Health.The Health component it links to is set up in config files (in the case of Unity, it would be in the Editor). This lack of loose coupling is fine, if you never intend on reusing your code.

Let’s say it’s time for your next project and, quelle surprise, you need a health label that maps to your player’s health, but this time Health has different functionality. Health.Life now refers to how much life they gain per second, and Health.HealthRemaining is how much life is remaining, and what’s worse, is there are ten other classes making use of Health.HealthRemaining, and the other developers are used to that system (having not worked on the previous project’s Health components). So what can you do, huh? You can start shouting and writing coding style documents, or you can copy HealthLabel and rewrite it to use Health.HealthRemaining instead. Two weeks later, a major bug is found in your HealthLabel code, and it affects both games. You have to make this change twice, and run your tests on both classes.

10 games later, and the 10 different versions of HealthLabel are becoming a pain to maintain, so what’s the solution?

public class Health { public int HealthRemaining { get; set; } public int Life { get; set; } public Health() { Life = 2; HealthRemaining = 10; } public void Hurt() { HealthRemaining--; Messenger.Default.Send(new HealthChanged(HealthRemaining)); } public void Heal() { HealthRemaining += Life; } } public class HealthChanged { public int DeltaHealth { get; set; } public HealthChanged(int deltaHealth) { DeltaHealth = deltaHealth; } } //Meanwhile in the view public class HealthLabel { public HealthLabel() { Messenger.Default.Register(HandleMessage); } private void HandleMessage(HealthChanged message) { Print(message.DeltaHealth); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 public class Health { public int HealthRemaining { get ; set ; } public int Life { get ; set ; } public Health ( ) { Life = 2 ; HealthRemaining = 10 ; } public void Hurt ( ) { HealthRemaining -- ; Messenger . Default . Send ( new HealthChanged ( HealthRemaining ) ) ; } public void Heal ( ) { HealthRemaining += Life ; } } public class HealthChanged { public int DeltaHealth { get ; set ; } public HealthChanged ( int deltaHealth ) { DeltaHealth = deltaHealth ; } } //Meanwhile in the view public class HealthLabel { public HealthLabel ( ) { Messenger . Default . Register ( HandleMessage ) ; } private void HandleMessage ( HealthChanged message ) { Print ( message . DeltaHealth ) ; } }

In this example, Health sends a HealthChanged message using Messenger.Default.Send<HealthChanged>(new HealthChanged(HealthRemaining)) whenever it gets hurt or healed. The Messenger then reroutes that message to whatever has registered for it. In this case, our HealthLabel. The Messenger executes the HealthLabel.HandleMessage function, which changes the displayed Health value depending on the parameter of the HealthChanged message. A year later, Health is modified to use Life again. HealthLabel doesn’t have to change at all, we simply fire the HealthChanged message whenever Health.Life is changed. Health and HealthLabel have loose coupling thanks to the intermediate HealthChanged message.

But that’s not all we can do. Now, just like an event, all our other classes with a dependency on Health (for example a red screen flash when you’re hit, or particle effects when you’re healed) can register their functionality to this HealthChanged message. And none of them will need to be changed when Health is modified. Their dependency on the Health class has been abstracted away to only what they need to know – i.e. when the health changes, and by how much.

Scope

You may have noticed that up until now, we’ve been using the default messenger, accessed using Messenger.Default. The default messenger is a globally-scoped static messenger than can be accessed anywhere and everywhere, but you can have others. One common use is to create a messenger at the root object of a prefab for inter-prefab messaging without messages being intercepted by other instances of that prefab. A great example for this is if you have a prefab bullet that, when hit, sends a BulletHit message and then destroys the mesh renderer and collider. You have in the same prefab a particle system that shows some hit effects and registers for BulletHit messages in order to do so. If you used the default messenger then every time a bullet hit something, all bullets in the scene would activate their hit effects. It would be chaotic. Instead, create a Messenger at the root of the prefab, and reference it when registering or sending messages,

Inversion of Control

Additionally, the messenger supports the Service Locator pattern. The Service Locator is a way of letting a class get its dependencies from a central location. It’s a type of Inversion of Control which leads to more configurable, generic classes, What’s Inversion of Control? Here’s a quick example:

public class MyClass { public int NumCores; public MyClass() { NumCores = 4; } } public class MyClass { public int NumCores; public MyClass(int numCores) { NumCores = numCores; } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 public class MyClass { public int NumCores ; public MyClass ( ) { NumCores = 4 ; } } public class MyClass { public int NumCores ; public MyClass ( int numCores ) { NumCores = numCores ; } }

The top class sets the value NumCores in its constructor to 4. Great for everybody running quad core systems. Not so great for legacy systems or the Glorious PC Gaming Master Race running hexadeca core systems. MyClass is Inflexible and depends on NumCores being 4. The bottom class, however, is more free. Our dependency NumCores is set through a constructor, so some other part of the game logic can work out how many cores to support and your fora are no longer filled with the burning vitriol of a poorly-supported PC gamer. In this case, control over the value of NumCores is wrested from MyClass and left somewhere else. Perhaps for a more suitable CoreProperties class to manage. This is a type of Dependency Injection called Constructor Injection.

Back to the Service Locator. The Service Locator is different to the Dependency Injection pattern in that it centralizes where these dependencies are set. Instead of being given its dependency, MyClass would instead ask the Service Locator how many cores should be supported. Provided someone, somewhere had registered the number of cores, the Service Locator would be able to inform MyClass and fill that dependency.

Note: If you don’t mind reflection in your project (which can be slow) then I would definitely recommend a Dependency Injection container over the Service Locator pattern. A good example is Strange IoC. The Messenger makes no use of Reflection for acquiring dependencies by using the Service Locator pattern.

How does Messenger support the Service Locator pattern? By using the Request<R>() function, which checks the dependency list for appropriate values and assigns them. On the other side of this is the Register<T,R>() function, which maps a request of type T to a return type of type R. This lets the user send a parameterised request for a dependency. Here’s a good example of when to use that.

//To start with public class PlayerManager { private Player[] players; public PlayerManager() { players = new Player[4]; for (int i = 0; i < 4; i++) { players[i] = new Player(); } Messenger.Default.Register<int, player>(PickPlayer); } private Player PickPlayer(int id) { return players[id]; } } //Elsewhere... public class InputManager { private Controller[] controllers; public InputManager() { for (int i = 0; i < 4; i++) { controllers[i] = new Controller(id); } } } public class Controller { private Player player; public Controller(int id) { player = Messenger.Default.Request<int, player>(id); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 //To start with public class PlayerManager { private Player [ ] players ; public PlayerManager ( ) { players = new Player [ 4 ] ; for ( int i = 0 ; i < 4 ; i ++ ) { players [ i ] = new Player ( ) ; } Messenger . Default . Register < int , player > ( PickPlayer ) ; } private Player PickPlayer ( int id ) { return players [ id ] ; } } //Elsewhere... public class InputManager { private Controller [ ] controllers ; public InputManager ( ) { for ( int i = 0 ; i < 4 ; i ++ ) { controllers [ i ] = new Controller ( id ) ; } } } public class Controller { private Player player ; public Controller ( int id ) { player = Messenger . Default . Request < int , player > ( id ) ; } }

The PlayerManager creates four players for a multiplayer game, players 1, 2, 3, and 4, and gives them unique ids. It then registers a function PickPlayer which takes an id integer as a parameter with the default Messenger. At the same time, the input manager creates 4 Controllers and assigns them each a number based on which slot they’re plugged into. When controller 3 is created it sends a request to the default Messenger for the player with id 3. Messenger executes the PickPlayer function and returns Player3.

What’s more is that you don’t have to just use the Messenger to request data on start up, you can also use it to get the result of functions from all over the place. For example, you might want to convert one type to another, and you don’t care how it’s done. Just send a Request!

Combine this functionality with the ability to have multiple Messenger scopes, and you can quickly see the flexibility of this system. You can scope your requests to different areas, from the Application scope of Messenger.Default, to Prefab scope or event to GameObject scope.

The Messenger Class

using System; using System.Collections.Generic; /// <summary> /// Strongly-typed messenger that also allows for IoC Service Locator requesting /// </summary> public class Messenger { /// <summary> /// The default messenger /// </summary> private static Messenger defaultMessenger; /// <summary> /// Gets the default messenger. /// </summary> /// <value> /// The default messenger. /// </value> public static Messenger Default { get { if (defaultMessenger == null) { defaultMessenger = new Messenger(); } return defaultMessenger; } } /// <summary> /// The public messengers /// </summary> private static Dictionary<string, Messenger> publicMessengers; /// <summary> /// Gets the <see cref="Messenger"/> with the specified key. /// </summary> /// <value> /// The <see cref="Messenger"/>. /// </value> /// <param name="key">The key.</param> /// <returns>The messenger corresponding to that key if it exists, else a new messenger.</returns> public Messenger this[string key] { get { if (publicMessengers == null) { publicMessengers = new Dictionary<string, Messenger>(); } if (!publicMessengers.ContainsKey(key)) { publicMessengers.Add(key, new Messenger()); } return publicMessengers[key]; } } /// <summary> /// The actions /// </summary> private Dictionary<Type, Delegate> actions; /// <summary> /// The functions /// </summary> private Dictionary<Type, Delegate> functions; /// <summary> /// Initializes a new instance of the <see cref="Messenger"/> class. /// </summary> public Messenger() { actions = new Dictionary<Type, Delegate>(); functions = new Dictionary<Type, Delegate>(); } /// <summary> /// Sends the specified message. /// </summary> /// <typeparam name="T">The type of message.</typeparam> /// <param name="message">The message.</param> public void Send<T>(T message) { if (actions.ContainsKey(typeof(T))) { ((Action<T>)actions[typeof(T)])(message); } } /// <summary> /// Sends an asynchronous message. /// </summary> /// <typeparam name="T">The type of message.</typeparam> /// <param name="message">The message.</param> /// <param name="callback">The callback to be executed when the message receive function has completed</param> public IAsyncResult SendAsync<T>(T message, AsyncCallback callback = null) { if (actions.ContainsKey(typeof(T))) { return ((Action<T>)actions[typeof(T)]).BeginInvoke(message, callback, null); } return null; } /// <summary> /// Send a request. /// </summary> /// <typeparam name="T">The type of the parameter of the request.</typeparam> /// <typeparam name="R">The return type of the request.</typeparam> /// <returns>The result of the request.</returns> public R Request<T, R>(T parameter) { if (functions.ContainsKey(typeof(T))) { var function = functions[typeof(T)] as Func<T, R>; if (function != null) { return function(parameter); } } return default(R); } /// <summary> /// Sends an asynchronous request. /// </summary> /// <typeparam name="T">The type of message being sent</typeparam> /// <param name="callback">The callback to be executed when the request finishes.</param> /// <returns>An IAsyncResult for the asynchronous operation.</returns> public IAsyncResult RequestAsync<T, R>(T parameter, AsyncCallback callback = null) { if (functions.ContainsKey(typeof(T))) { var function = functions[typeof(T)] as Func<T, R>; if (function != null) { return function.BeginInvoke(parameter, callback, null); } } return null; } /// <summary> /// Register a function for a request message /// </summary> /// <typeparam name="T">Type of message to receive</typeparam> /// <param name="request">The function that fills the request</param> public void Register<T, R>(Func<T, R> request) { if (functions.ContainsKey(typeof(T))) { functions[typeof(T)] = Delegate.Combine(functions[typeof(T)], request); } else { functions.Add(typeof(T), request); } } /// <summary> /// Register an action for a message. /// </summary> /// <typeparam name="T">Type of message to receive</typeparam> /// <param name="action">The action that happens when the message is received.</param> public void Register<T>(Action<T> action) { if (actions.ContainsKey(typeof(T))) { actions[typeof(T)] = (Action<T>)Delegate.Combine(actions[typeof(T)], action); } else { actions.Add(typeof(T), action); } } /// <summary> /// Unregister a request /// </summary> /// <typeparam name="T">The type of request to unregister.</typeparam> /// <typeparam name="R">The return type of the request.</typeparam> /// <param name="request">The request to unregister.</param> public void Unregister<T,R>(Func<T,R> request) { if(functions.ContainsKey(typeof(T))) { functions[typeof(T)] = Delegate.Remove(functions[typeof(T)], request); } } /// <summary> /// Unregister an action. /// </summary> /// <typeparam name="T">The type of message.</typeparam> /// <param name="action">The action to unregister.</param> public void Unregister<T>(Action<T> action) { if(actions.ContainsKey(typeof(T))) { actions[typeof(T)] = (Action<T>)Delegate.Remove(actions[typeof(T)], action); } } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 using System ; using System . Collections . Generic ; /// <summary> /// Strongly-typed messenger that also allows for IoC Service Locator requesting /// </summary> public class Messenger { /// <summary> /// The default messenger /// </summary> private static Messenger defaultMessenger ; /// <summary> /// Gets the default messenger. /// </summary> /// <value> /// The default messenger. /// </value> public static Messenger Default { get { if ( defaultMessenger == null ) { defaultMessenger = new Messenger ( ) ; } return defaultMessenger ; } } /// <summary> /// The public messengers /// </summary> private static Dictionary < string , Messenger > publicMessengers ; /// <summary> /// Gets the <see cref="Messenger"/> with the specified key. /// </summary> /// <value> /// The <see cref="Messenger"/>. /// </value> /// <param name="key">The key.</param> /// <returns>The messenger corresponding to that key if it exists, else a new messenger.</returns> public Messenger this [ string key ] { get { if ( publicMessengers == null ) { publicMessengers = new Dictionary < string , Messenger > ( ) ; } if ( ! publicMessengers . ContainsKey ( key ) ) { publicMessengers . Add ( key , new Messenger ( ) ) ; } return publicMessengers [ key ] ; } } /// <summary> /// The actions /// </summary> private Dictionary < Type , Delegate > actions ; /// <summary> /// The functions /// </summary> private Dictionary < Type , Delegate > functions ; /// <summary> /// Initializes a new instance of the <see cref="Messenger"/> class. /// </summary> public Messenger ( ) { actions = new Dictionary < Type , Delegate > ( ) ; functions = new Dictionary < Type , Delegate > ( ) ; } /// <summary> /// Sends the specified message. /// </summary> /// <typeparam name="T">The type of message.</typeparam> /// <param name="message">The message.</param> public void Send < T > ( T message ) { if ( actions . ContainsKey ( typeof ( T ) ) ) { ( ( Action < T > ) actions [ typeof ( T ) ] ) ( message ) ; } } /// <summary> /// Sends an asynchronous message. /// </summary> /// <typeparam name="T">The type of message.</typeparam> /// <param name="message">The message.</param> /// <param name="callback">The callback to be executed when the message receive function has completed</param> public IAsyncResult SendAsync < T > ( T message , AsyncCallback callback = null ) { if ( actions . ContainsKey ( typeof ( T ) ) ) { return ( ( Action < T > ) actions [ typeof ( T ) ] ) . BeginInvoke ( message , callback , null ) ; } return null ; } /// <summary> /// Send a request. /// </summary> /// <typeparam name="T">The type of the parameter of the request.</typeparam> /// <typeparam name="R">The return type of the request.</typeparam> /// <returns>The result of the request.</returns> public R Request < T , R > ( T parameter ) { if ( functions . ContainsKey ( typeof ( T ) ) ) { var function = functions [ typeof ( T ) ] as Func < T , R > ; if ( function != null ) { return function ( parameter ) ; } } return default ( R ) ; } /// <summary> /// Sends an asynchronous request. /// </summary> /// <typeparam name="T">The type of message being sent</typeparam> /// <param name="callback">The callback to be executed when the request finishes.</param> /// <returns>An IAsyncResult for the asynchronous operation.</returns> public IAsyncResult RequestAsync < T , R > ( T parameter , AsyncCallback callback = null ) { if ( functions . ContainsKey ( typeof ( T ) ) ) { var function = functions [ typeof ( T ) ] as Func < T , R > ; if ( function != null ) { return function . BeginInvoke ( parameter , callback , null ) ; } } return null ; } /// <summary> /// Register a function for a request message /// </summary> /// <typeparam name="T">Type of message to receive</typeparam> /// <param name="request">The function that fills the request</param> public void Register < T , R > ( Func < T , R > request ) { if ( functions . ContainsKey ( typeof ( T ) ) ) { functions [ typeof ( T ) ] = Delegate . Combine ( functions [ typeof ( T ) ] , request ) ; } else { functions . Add ( typeof ( T ) , request ) ; } } /// <summary> /// Register an action for a message. /// </summary> /// <typeparam name="T">Type of message to receive</typeparam> /// <param name="action">The action that happens when the message is received.</param> public void Register < T > ( Action < T > action ) { if ( actions . ContainsKey ( typeof ( T ) ) ) { actions [ typeof ( T ) ] = ( Action < T > ) Delegate . Combine ( actions [ typeof ( T ) ] , action ) ; } else { actions . Add ( typeof ( T ) , action ) ; } } /// <summary> /// Unregister a request /// </summary> /// <typeparam name="T">The type of request to unregister.</typeparam> /// <typeparam name="R">The return type of the request.</typeparam> /// <param name="request">The request to unregister.</param> public void Unregister < T , R > ( Func < T , R > request ) { if ( functions . ContainsKey ( typeof ( T ) ) ) { functions [ typeof ( T ) ] = Delegate . Remove ( functions [ typeof ( T ) ] , request ) ; } } /// <summary> /// Unregister an action. /// </summary> /// <typeparam name="T">The type of message.</typeparam> /// <param name="action">The action to unregister.</param> public void Unregister < T > ( Action < T > action ) { if ( actions . ContainsKey ( typeof ( T ) ) ) { actions [ typeof ( T ) ] = ( Action < T > ) Delegate . Remove ( actions [ typeof ( T ) ] , action ) ; } } }

Note: The Async functions cannot be used when a MonoBehaviour has registered to the message type because a MonoBehaviour cannot run on a different thread. An error will occur.

A Unity Helper Class

This little helper class is not part of the main project, but something I’ve found useful when using Unity. It’s a component that, when a certain message comes through, activates a specified game object. The type of message it listens for is converted through reflection from a string, so this one component can be used for any type of message. Note: If you use namespaces, make sure to namespace-qualify the input string (e.g. System.String or Messages.GameOverMessage).

using UnityEngine; using System.Collections; using System; using System.Runtime.Remoting; using System.Linq; /// /// Activates a Game Object when a message of configurable type is received. /// Note: Uses Reflection, so if speed is a priority, use an alternative method. /// public class ActivateOnMessage : MonoBehaviour { /// /// The type of message to receive. /// [SerializeField] private string messageType; [SerializeField] private GameObject target; /// /// The GameObject to activate when the message is received. /// public GameObject Target { get { return target; } set { target = value; } } private Delegate activateDelegate; private Type type; private void Awake() { //Convert the input text into a type. type = Type.GetType(messageType); if (type != null) { //create a delegate for activating our target activateDelegate = Delegate.CreateDelegate(typeof(Action<>).MakeGenericType(type), this, typeof(ActivateOnMessage) .GetMethod("GenericSetActive") .MakeGenericMethod(type)); //Register the delegate with the default messenger. Register(false); } else { Debug.Log("Error: Type string does not map to a correct Type"); } } /// /// Generic set active function /// Bit of a hack to get around not being able to use an anonymous method. /// ///The type for this function. (Unused). ///The type to put in. (Unused). public void GenericSetActive(T ignored) { Target.SetActive(true); } /// /// Registers the activate delegate on the default messenger for the message type in type. /// ///Whether to register or unregister private void Register(bool unregister) { string methodName = unregister ? "Unregister" : "Register"; typeof(Messenger).GetMethods() .Where(x => x.Name == methodName).Select(x => new { M = x, P = x.GetParameters() }) .Where(x => x.P.Length == 1 && x.P[0].ParameterType.ContainsGenericParameters && x.P[0].ParameterType.FullName.Contains("System.Action")) .Select(x => x.M) .SingleOrDefault() .MakeGenericMethod(type) .Invoke(Messenger.Default, new object[] { activateDelegate }); } /// /// Unregister from the messenger. /// void OnDestroy() { if (type != null) { Register(true); } } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 using UnityEngine ; using System . Collections ; using System ; using System . Runtime . Remoting ; using System . Linq ; /// /// Activates a Game Object when a message of configurable type is received. /// Note: Uses Reflection, so if speed is a priority, use an alternative method. /// public class ActivateOnMessage : MonoBehaviour { /// /// The type of message to receive. /// [ SerializeField ] private string messageType ; [ SerializeField ] private GameObject target ; /// /// The GameObject to activate when the message is received. /// public GameObject Target { get { return target ; } set { target = value ; } } private Delegate activateDelegate ; private Type type ; private void Awake ( ) { //Convert the input text into a type. type = Type . GetType ( messageType ) ; if ( type != null ) { //create a delegate for activating our target activateDelegate = Delegate . CreateDelegate ( typeof ( Action <> ) . MakeGenericType ( type ) , this , typeof ( ActivateOnMessage ) . GetMethod ( "GenericSetActive" ) . MakeGenericMethod ( type ) ) ; //Register the delegate with the default messenger. Register ( false ) ; } else { Debug . Log ( "Error: Type string does not map to a correct Type" ) ; } } /// /// Generic set active function /// Bit of a hack to get around not being able to use an anonymous method. /// ///The type for this function. (Unused). ///The type to put in. (Unused). public void GenericSetActive ( T ignored ) { Target . SetActive ( true ) ; } /// /// Registers the activate delegate on the default messenger for the message type in type. /// ///Whether to register or unregister private void Register ( bool unregister ) { string methodName = unregister ? "Unregister" : "Register" ; typeof ( Messenger ) . GetMethods ( ) . Where ( x = > x . Name == methodName ) . Select ( x = > new { M = x , P = x . GetParameters ( ) } ) . Where ( x = > x . P . Length == 1 && x . P [ 0 ] . ParameterType . ContainsGenericParameters && x . P [ 0 ] . ParameterType . FullName . Contains ( "System.Action" ) ) . Select ( x = > x . M ) . SingleOrDefault ( ) . MakeGenericMethod ( type ) . Invoke ( Messenger . Default , new object [ ] { activateDelegate } ) ; } /// /// Unregister from the messenger. /// void OnDestroy ( ) { if ( type != null ) { Register ( true ) ; } } }