Exemple #1
0
        public static T Instance()
        {
            if (instance == null)
            {
                instance = FindObjectOfType <T>();

                if (FindObjectsOfType <T>().Length > 1)
                {
                    if (APP_CONFIG.DEBUG)
                    {
                        QPrint.FrameworkError("More than 1!");
                    }
                    return(instance);
                }

                if (instance == null)
                {
                    string instanceName = typeof(T).Name;
                    if (APP_CONFIG.DEBUG)
                    {
                        QPrint.FrameworkLog("Instance Name: " + instanceName);
                    }
                    GameObject instanceGO = GameObject.Find(instanceName);

                    if (instanceGO == null)
                    {
                        instanceGO = new GameObject(instanceName);
                    }
                    instance = instanceGO.AddComponent <T>();
                    DontDestroyOnLoad(instanceGO);                      // 不会被释放
                    if (APP_CONFIG.DEBUG)
                    {
                        QPrint.FrameworkLog("Add New Singleton " + instance.name + " in Game!");
                    }
                }
                else
                {
                    if (APP_CONFIG.DEBUG)
                    {
                        QPrint.FrameworkLog("Already exist: " + instance.name);
                    }
                }
            }

            return(instance);
        }
        /// <summary>
        /// 发送消息
        /// 注意第一个参数
        /// </summary>
        public static void SendLogicMsg(this IMsgSender sender, string msgName, params object[] paramList)
        {
            // 略过,不用看
            if (string.IsNullOrEmpty(msgName))
            {
                QPrint.FrameworkError("SendMsg is Null or Empty");
                return;
            }

            // 略过,不用看
            if (!mMsgHandlerDict.ContainsKey(msgName))
            {
                QPrint.FrameworkWarn("SendMsg is UnRegister");
                return;
            }

            // 开始看!!!!
            var handlers = mMsgHandlerDict[msgName];


            var handlerCount = handlers.Count;

            // 之所以是从后向前遍历,是因为  从前向后遍历删除后索引值会不断变化
            // 参考文章,http://www.2cto.com/kf/201312/266723.html
            for (int index = handlerCount - 1; index >= 0; index--)
            {
                var handler = handlers[index];

                if (handler.receiver != null)
                {
                    QPrint.FrameworkLog("SendLogicMsg:" + msgName + " Succeed");
                    handler.callback(paramList);
                }
                else
                {
                    handlers.Remove(handler);
                }
            }
        }