[Unity] thread-safe message transmission mechanism, which is based on Cocos and unitycocos

Source: Internet
Author: User

[Unity] thread-safe message transmission mechanism, which is based on Cocos and unitycocos

Recently, network communication methods have been used. Although unity can use coroutine to implement asynchronous operations, it is not used by teammates. He uses the traditional thread-opening method, in this way, thread security issues will occur, and the existing message communication mechanism will not be able to meet the requirements, so we have to change it. Fortunately, I have read the implementation principle of the message mechanism in Cocos2dx and changed it by hand. The following is the source code: (explained after source code)

Using System; using System. collections; using System. collections. generic; using UnityEngine;/*** message dispatching class */namespace Assets. TGUI. UIScript {public class CDispatcher {// Single Instance public static readonly CDispatcher Instance = new CDispatcher (); // message delegate function public delegate void noticeDelegate (object [] data ); /// <summary> /// Message Key /// </summary> public struct Key {public string name; public object target; public Key (string _ name, object _ target) {name = _ name; target = _ target ;}// store the message list private Dictionary <Key, noticeDelegate> m_noticeDict; private List <KeyValuePair <Key, object []> m_noticeRequest; private List <KeyValuePair <Key, object []> m_tempRequest; private CDispatcher () {m_noticeDict = new Dictionary <Key, noticeDelegate> (); m_noticeRequest = new List <KeyValuePair <Key, object []> (); m_tempReques T = new List <KeyValuePair <Key, object []> ();} /// <summary> /// cyclically traverse and execute the message request // </summary> public IEnumerator Dispatcher () {Debug. log ("MSG: Start Dispatcher"); do {if (m_tempRequest.Count! = 0) {lock (m_tempRequest) {foreach (var item in m_tempRequest) {m_noticeRequest.Add (new KeyValuePair <Key, object []> (item. key, item. value);} m_tempRequest.Clear ();} foreach (var item in m_noticeRequest) {if (m_noticeDict.ContainsKey (item. key) {m_noticeDict [item. key] (item. value) ;}} m_noticeRequest.Clear ();} yield return new WaitForFixedUpdate () ;}while (true) ;}/ *** send message ** @ param noti FyName Message Type * @ param data carries the parameter */public void sendNotification (string noticeName, object [] data = null) {sendNotification (noticeName, null, data );} /// <summary> /// send the message // </summary> /// <param name = "noticeName"> </param> /// <param name = "target"> </param> // <param name = "data"> </param> public void sendNotification (string noticeName, object target, object [] data) {m_tempRequest.Add (new KeyVal UePair <Key, object []> (new Key (noticeName, target), data ));} /// <summary> /// the data contained in the sent message is the sender's object // </summary> /// <param name = "noticeName"> </param >/// <param name = "target"> </param> /// <param name = "source"> </param> public void sendNotification (string noticeName, object target, object source) {sendNotification (noticeName, target, new object [] {source });} /// <summary> /// get the source type variable /// NdNotification (string noticeName, // object target, object source) corresponds) /// </summary> /// <typeparam name = "T"> </typeparam> /// <param name = "data"> </param> /// <returns> </returns> public T GetSourceObject <T> (object [] data) {return (T) data [0];} public void addObserver (string noticeName, noticeDelegate notice) {addObserver (noticeName, null, notice);} public void addObserver (string noticeName, obj Ect target, noticeDelegate notice) {Key key = new Key (noticeName, target); if (! Secret (key) {m_noticeDict.Add (key, notice) ;}} public void RemoveObserver (string noticeName) {RemoveObserver (noticeName, null);} public void RemoveObserver (string noticeName, object target) {Key key Key = new Key (noticeName, target); if (! M_noticeDict.ContainsKey (key) {m_noticeDict.Remove (key );}}}}

The method is a little more, but the method worth attention is the following:

IEnumerator Dispatcher()public void sendNotification(...)public void addObserver(...)public void RemoveObserver(...)


First, the first method is the message loop Traversal method. You need to enable the message loop traversal by using coroutine in the start method of the main object of the game. The statement is as follows:

// Enable the message loop StartCoroutine (CDispatcher. Instance. Dispatcher ());

Then, like Cocos2dx, add the observer

CDispatcher. Instance. addObserver ("message name", [target object], method );

Then send the message

CDispatcher. Instance. sendNotification ("message name", [target object], [Additional data]);


The following is a complete example:

Protected void Start () {// enable the message loop StartCoroutine (CDispatcher. instance. dispatcher (); CDispatcher. instance. addObserver ("I want to go to bed", x => Debug. log ("sleeping"); CDispatcher. instance. sendNotification ("I want to go to bed ");}

Finally, the output is "sleeping ".


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.