What is a messaging mechanism?

23333333. Let me laugh for a second.

Why messaging?

In three words, solve!!!! Decoupling!!!!!!!!!! Us!!!!!!!!!! .

The message mechanism use case in my framework:

1. The receiver

using UnityEngine; Namespace QFramework. Example {/ / / < summary > / / / tutorial address: / / http://liangxiegame.com/post/5/ / < summary > public class Receiver : MonoBehaviour, IMsgReceiver { // Use this for initialization private void Awake() { this.RegisterLogicMsg("Receiver Show Sth", ReceiveMsg); } private void ReceiveMsg(object[] args) { foreach (var arg in args) { Log.I(arg); }}}}Copy the code

2. The sender

using UnityEngine; Namespace QFramework. Example {/ / / < summary > / / / tutorial address: / / http://liangxiegame.com/post/5/ / < summary > public class Sender Void Update() {this.sendLogicmsg ("Receiver Show Sth", "hello "," world "); }}}Copy the code

3. Running result

How is it done?

You can see that the receiver implements the interface IMsgReceiver and the sender implements the interface IMsgSender. So let’s look at these two interface definitions.

IMsgReceiver:

namespace QFramework 
{
	public interface IMsgReceiver{}}Copy the code

IMsgSender

namespace QFramework 
{
	public interface IMsgSender{}}Copy the code

Nothing. There is no definition of the SendLogicMsg or ReceiveLogicMsg methods.

The answer is to implement interface methods using an extension of C# this.

Unclear children’s shoes please baidu C# this extension, there are a lot of articles will not be introduced.

Let’s end with an important role,MsgDispatcher.

Paste the first part of the code:

/// <summary>
	///Message distributor
	///The C# this extension requires a static class
	///Tutorial address: http://liangxiegame.com/post/5/
	public static class MsgDispatcher
	{
		/// <summary>
		///Message catcher
		/// </summary>
		private class LogicMsgHandler
		{
			public readonly IMsgReceiver Receiver;
			public readonly Action<object[]> Callback;

			public LogicMsgHandler(IMsgReceiver receiver, Action<object[]> callback)
			{ Receiver = receiver; Callback = callback; }}/// <summary>
		///Each message name maintains a set of message catchers.
		/// </summary>
		static readonly Dictionary<string, List<LogicMsgHandler>> mMsgHandlerDict =
			new Dictionary<string, List<LogicMsgHandler>>();
Copy the code

Read the comments!!!!!!

Paste the code for the registration message

/// <summary>
		///Register message,
		///Notice the first argument, which uses the C# this extension,
		///So only objects that implement IMsgReceiver can call this method
		/// </summary>
		public static void RegisterLogicMsg(this IMsgReceiver self, string msgName, Action<object[]> callback)
		{
			/ / skip
			if (string.IsNullOrEmpty(msgName))
			{
				Log.W("RegisterMsg:" + msgName + " is Null or Empty");
				return;
			}

			/ / skip
			if (null == callback)
			{
				Log.W("RegisterMsg:" + msgName + " callback is Null");
				return;
			}

			/ / skip
			if(! mMsgHandlerDict.ContainsKey(msgName)) { mMsgHandlerDict[msgName] =new List<LogicMsgHandler>();
			}

			// Take a look here
			var handlers = mMsgHandlerDict[msgName];

			/ / skip
			// Prevent duplicate registrations
			foreach (var handler in handlers)
			{
				if (handler.Receiver == self && handler.Callback == callback)
				{
					Log.W("RegisterMsg:" + msgName + " ayready Register");
					return; }}// Take a look here
			handlers.Add(new LogicMsgHandler(self, callback));
		}
Copy the code

To save you time, skip some of the code. What? !!!!! You’ve seen!!!! 23333

The code associated with sending the message

/// <summary>
		///Send a message
		///Notice the first parameter
		/// </summary>
		public static void SendLogicMsg(this IMsgSender sender, string msgName, params object[] paramList)
		{
			// Skip it
			if (string.IsNullOrEmpty(msgName))
			{
				Log.E("SendMsg is Null or Empty");
				return;
			}

			// Skip it
			if(! mMsgHandlerDict.ContainsKey(msgName)) { Log.W("SendMsg is UnRegister");
				return;
			}

			// Start at!!!!
			var handlers = mMsgHandlerDict[msgName];
			var handlerCount = handlers.Count;

			// The index value changes after the index is deleted
			/ / refer to the article, http://www.2cto.com/kf/201312/266723.html
			for (var index = handlerCount - 1; index >= 0; index--)
			{
				var handler = handlers[index];

				if(handler.Receiver ! =null)
				{
					Log.W("SendLogicMsg:" + msgName + " Succeed");
					handler.Callback(paramList);
				}
				else{ handlers.Remove(handler); }}}Copy the code

OK, the main parts are all posted

Areas for improvement:

  • Currently, messages throughout the game are maintained by a dictionary, which could be improved to maintain a dictionary per module or other means.
  • The message name type is defined by a string and can be changed to an enumeration to unsigned int.
  • Welcome to add.

pit

  • If it is MonoBehaviour after the message is registered, the message must be unregistered before GameObject Destroy. The previous solution was to create a custom base class to maintain a list of registered messages for the object, and then iterate through the uninstallation in the OnDestory of the base class.
  • Welcome to add.

Related links:

The framework of my address: https://github.com/liangxiegame/QFramework

Tutorial source: https://github.com/liangxiegame/QFramework/tree/master/Assets/HowToWriteUnityGameFramework/

QFramework& Game framework to build QQ communication group: 623597263

Please indicate address for reprinting: Notes on sandals http://liangxiegame.com/

My wechat official account is LiangXieGame

If it can help you:

If you find this tutorial or QFramework helpful, you may want to sponsor the author in the following ways to encourage the author to continue to write more high-quality tutorials and add more power to the QFramework.

  • Give QFramework a Star:https://github.com/liangxiegame/QFramework
  • Download QFramework from The Asset Store and give it a five star rating (if any reviews are small, thank you very much):http://u3d.as/SJ9
  • Buy gitchat topic and give 5 star high praise: http://gitbook.cn/gitchat/activity/5abc3f43bad4f418fb78ab77 (6 yuan, members free of charge)
  • Buy the bull with the same video courses and give 5 star high praise: http://edu.manew.com/course/431 (at present price 29.8 yuan)
  • To buy the same ebook: https://www.kancloud.cn/liangxiegame/unity_framework_design (29.9 yuan, content will end in October 2018)

I guarantee that the QFramework, the introductory tutorials, the documentation, and the columns in the framework building series will always be free and open source. None of the above donated product content is necessary to use the QFramework, so don’t worry, you are already supporting my team by using the QFramework or reading this column.