Unity3D游戏开发框架-消息机制

原创 2016年08月29日 12:06:04

转载请注明原文链接:http://blog.csdn.net/u013108312/article/details/52351826
这里写图片描述
这里写图片描述

using UnityEngine;
using System.Collections;

/// <summary>
/// 消息监听接口
/// </summary>
public interface IEventListener   
{
    /// <summary>
    /// 处理消息
    /// </summary>
    /// <param name="id">消息Id</param>
    /// <param name="param1">参数1</param>
    /// <param name="param2">参数2</param>
    /// <returns>是否终止消息派发</returns>
    bool HandleEvent(int id, object param1, object param2);

    /// <summary>
    /// 消息优先级
    /// </summary>
    /// <returns></returns>
    int EventPriority();
}
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class EventNode : MonoBehaviour
{
    /// <summary>
    /// 节点优先级
    /// </summary>
    public int EventNodePriority { set; get; }

    /// <summary>
    /// 所有消息集合
    /// </summary>
    private Dictionary<int, List<IEventListener>> mListeners = new Dictionary<int, List<IEventListener>>();

    /// <summary>
    /// 消息节点
    /// </summary>
    private List<EventNode> mNodeList = new List<EventNode>();

    /// <summary>
    /// 挂载一个消息节点到当前节点上
    /// </summary>
    /// <param name="node">消息节点</param>
    /// <returns>如果当前节点里面已经包含要添加的这个节点那么返回false</returns>
    public bool AttachEventNode(EventNode node)
    {
        if (node == null)
        {
            return false;
        }

        if (mNodeList.Contains(node))
        {
            return false;
        }
        int pos = 0;
        for (int i = 0; i < mNodeList.Count;i++ )
        {
            if (node.EventNodePriority > mNodeList[i].EventNodePriority)
            {
                break;
            }
            pos++;
        }

        mNodeList.Insert(pos,node);
        return true;
    }

    /// <summary>
    /// 卸载一个消息节点
    /// </summary>
    /// <param name="node">消息节点</param>
    /// <returns>如果节点不存在那么返回false</returns>
    public bool DetachEventNode(EventNode node)
    {
        if (!mNodeList.Contains(node))
        {
            return false;
        }
        mNodeList.Remove(node);
        return true;
    }

    /// <summary>
    /// 挂载一个消息监听器到当前的消息节点
    /// </summary>
    /// <param name="key">消息ID</param>
    /// <param name="listener">消息监听器</param>
    /// <returns>当前消息节点已经挂载了这个消息监听器那么返回false</returns>
    public bool AttachEventListener(int key,IEventListener listener)
    {
        if (listener == null)
        {
            return false;
        }
        if (!mListeners.ContainsKey(key))
        {
            mListeners.Add(key,new List<IEventListener>() { listener });
            return true;
        }
        if (mListeners[key].Contains(listener))
        {
            return false;
        }
        int pos = 0;
        for (int i = 0;i< mListeners[key].Count;i++ )
        {
            if (listener.EventPriority() > mListeners[key][i].EventPriority())
            {
                break;
            }
            pos++;
        }
        mListeners[key].Insert(pos,listener);
        return true;
    }

    /// <summary>
    /// 卸载一个消息节点
    /// </summary>
    /// <returns>如果当前消息节点不存在那么返回false</returns>
    public bool DetachEventListener(int key,IEventListener listener)
    {
       if (mListeners.ContainsKey(key) && mListeners[key].Contains(listener))
       {
           mListeners[key].Remove(listener);
           return true;
       }
       return false;
    }

    public void SendEvent(int key,object param1 = null,object param2 = null)
    {
        DispatchEvent(key, param1, param2);
    }

    /// <summary>
    /// 派发消息到子消息节点以及自己节点下的监听器上
    /// </summary>
    /// <param name="key">消息ID</param>
    /// <param name="param1"></param>
    /// <param name="param2"></param>
    /// <returns>如果中断消息返回true</returns>
    private bool DispatchEvent(int key,object param1,object param2)
    {
        for (int i = 0; i < mNodeList.Count;i++ )
        {
            if (mNodeList[i].DispatchEvent(key, param1, param2)) return true;
        }
        return TriggerEvent(key, param1, param2);
    }


    /// <summary>
    /// 消息触发
    /// </summary>
    /// <param name="key">消息id</param>
    /// <param name="param1"></param>
    /// <param name="param2"></param>
    /// <returns>是否中断</returns>
    private bool TriggerEvent(int key,object param1,object param2)
    {
        if (!this.gameObject.activeSelf || !this.gameObject.activeInHierarchy || !this.enabled)
        {
            return false;
        }

        if (!mListeners.ContainsKey(key))
        {
            return false;
        }
        List<IEventListener> listeners = mListeners[key];
        for (int i = 0; i < listeners.Count; i++)
        {
            if (listeners[i].HandleEvent(key, param1, param2)) return true;
        }
        return false;
    }

   void OnApplicationQuit()
    {
        mListeners.Clear();
        mNodeList.Clear();
    }

}

测试:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

public class EventDef
{
    public const int EventTest1 = 1;
    public const int EventTest2 = EventTest1 + 1;


    public const int ResLoadFinish = 1000;

}

using UnityEngine;
using System.Collections;

public class EventListener : MonoBehaviour,IEventListener 
{
    // Awake is called when the script instance is being loaded.
    void Awake() 
    {
        if (EventNodeCore.Instance)
        {
            EventNodeCore.Instance.AttachEventListener(EventDef.EventTest1, this);
        }
    }

    void OnDestroy()
    {
        if (EventNodeCore.Instance)
        {
            EventNodeCore.Instance.DetachEventListener(EventDef.EventTest1, this);
        }
    }
    public bool HandleEvent(int id, object param1, object param2)
    {
        Debug.Log("EventListener.HandleEvent =>" + " id=" + id + "param1=" + param1);
        switch(id)
        {
            case EventDef.EventTest1:
                Debug.Log(this.name + "=>" + "HandleEvent EventTest1");
                return false;
        }
        return false;
    }

    public int EventPriority()
    {
        return 0;
    }
}

using UnityEngine;
using System.Collections;

public class EventListener1 : MonoBehaviour , IEventListener
{
    // Awake is called when the script instance is being loaded.
    void Awake() 
    {
        if (EventNode1.Instance)
        {
            EventNode1.Instance.AttachEventListener(EventDef.EventTest1, this);
            EventNode1.Instance.AttachEventListener(EventDef.EventTest2, this);
        }
    }
    void OnDestroy()
    {
        if (EventNode1.Instance)
        {
            EventNode1.Instance.DetachEventListener(EventDef.EventTest1, this);
            EventNode1.Instance.DetachEventListener(EventDef.EventTest2, this);
        }
    }
    // Start is called on the frame when a script is enabled just before any of the Update methods is called the first time.
    void Start()
    {
    }

    // Update is called every frame, if the MonoBehaviour is enabled.
    void Update() 
    {
    }

    public bool HandleEvent(int id, object param1, object param2)
    {
        Debug.Log("EventListener1." + "HandleEvent => id =" + id + " param1=" + param1);
        //return true 消息中断
        return false;
    }

    public int EventPriority()
    {
        return 1;
    }
}

using UnityEngine;
using System.Collections;

public class EventListener2 : MonoBehaviour,IEventListener 
{
    // Awake is called when the script instance is being loaded.
    void Awake() 
    {
        if (EventNode2.Instance)
        {
            EventNode2.Instance.AttachEventListener(EventDef.EventTest1, this);
        }
    }

    void OnDestroy()
    {
        if (EventNode2.Instance)
        {
            EventNode2.Instance.DetachEventListener(EventDef.EventTest1, this);
        }
    }

    public bool HandleEvent(int id, object param1, object param2)
    {
        Debug.Log("EventListener2.HandleEvent => id =" + id + " param1=" + param1);
        return false;
    }

    public int EventPriority()
    {
        return 2;
    }
}

using UnityEngine;
using System.Collections;

public class EventNode1 : EventNode
{
    private static EventNode1 mInstance;
    public static EventNode1 Instance
    {
        get
        {
            return mInstance;
        }
    }

    void Awake()
    {
        mInstance = this;

        //base.EventNodePriority = 30;

        if (EventNodeCore.Instance)
        {
            EventNodeCore.Instance.AttachEventNode(this);
        }
        Debug.Log("-------------1");
    }

    void OnDestroy()
    {
        if (EventNodeCore.Instance)
        {
            EventNodeCore.Instance.DetachEventNode(this);
        }
    }
}

using UnityEngine;
using System.Collections;

public class EventNode2 : EventNode 
{
    private static EventNode2 mInstance;
    public static EventNode2 Instance
    {
        get
        {
            return mInstance;
        }
    }

    // Awake is called when the script instance is being loaded.
    void Awake() 
    {
        mInstance = this;
        base.EventNodePriority = 20;
        if (EventNodeCore.Instance)
        {
            EventNodeCore.Instance.AttachEventNode(this);
        }
    }
    void OnDestroy()
    {
        if (EventNodeCore.Instance)
        {
            EventNodeCore.Instance.DetachEventNode(this);
        }
    }


}

using UnityEngine;
using System.Collections;

public class EventNodeCore : EventNode
{
    private static EventNodeCore mInstance;
    public static EventNodeCore Instance
    {
        get
        {
            return mInstance;
        }

    }
    void Awake()
    {
        mInstance = this;
        Debug.Log("-------------");
    }

    void OnDestroy()
    {

    }

    void OnGUI()
    {
        if (GUI.Button(new Rect (0,0,200,50),"EventNodecore.SenEvent"))
        {
            EventNodeCore.Instance.SendEvent(EventDef.EventTest1, "测试消息发送");
        }
        if (GUI.Button(new Rect(0, 60, 200, 50), "EventNode1.SenEvent"))
        {
            EventNode1.Instance.SendEvent(EventDef.EventTest1, "测试消息发送");
            EventNode1.Instance.SendEvent(EventDef.EventTest2, "测试消息发送");
        }
        if (GUI.Button(new Rect(0, 120, 200, 50), "EventNode2.SenEvent"))
        {
            EventNode2.Instance.SendEvent(EventDef.EventTest1, "测试消息发送");
        }
    }
}

转载请注明原文链接:http://blog.csdn.net/u013108312/article/details/52351826

版权声明:欢迎转载,转载请注明原博客链接:http://blog.csdn.net/u013108312 和本文章的链接。谢谢合作。作者:CircleGood

Unity角色技能及技能编辑器设计之概念篇

概览首先给大家展示一下我们一个游戏中设计的技能及编辑器 构思我们很少能听到关于技能的一个定义或描述,那么,如果我们需要用程序思维来概括技能,我们应该怎么措辞才比较准确?当然,对于不同的游戏,技能的设...

【Unity3D实战】技能系统与技能编辑器的设计

作者有话说有一段时间没更新博客了,因为自六月下旬开始,一直在忙实习的事情,前几天登陆CSDN博客的时候,还发现因博客被人盗用大量发表无关外链导致博客被封了半个月,多亏CSDN的工作人员帮忙解锁了,在此...

Unity3D游戏开发框架-资源管理类ResourceManage

原文链接:http://blog.csdn.net/u013108312/article/details/52351850 新建文件夹:ResMgr。接着新建三个C#脚本。代码如下: IRes...

Unity3d游戏开发框架-UI管理类 UIManager

新建一个文件夹:UIMgr 新建2个C#脚本:BaseUI.cs UIMgr.csusing UnityEngine; using System.Collections;public class B...

unity3D 游戏开发之工程代码框架设计思路MVC

unity3D 游戏开发之工程代码框架设计思路MVC 设计目的 1.使工程结构更规范。 2.提高代码可读性,封装性,拓展性  3.提高工作效率。 正文内容:  1.Frame的组成结 (1)视图层(...

Unity3D游戏开发框架-FSM状态机的实现

新建一个C#脚本。IState.csusing UnityEngine; using System.Collections;public interface IState { /// ...

分享Unity3d的消息机制实现

在mvc模式中,消息机制被广泛使用,Unity3d自带的消息机制真心不好用,像SendMessage,需要知道响应事件的物件,还需要一个响应函数的函数名字符串作为参数,如果我们有多个物件都要响应某个事...
  • dfgjava
  • dfgjava
  • 2013年10月26日 13:52
  • 10474

cocos2d-x游戏开发系列教程-超级玛丽08-消息机制

在超级玛丽游戏里,地图类CMGameMap负责所有的程序逻辑,它包含了背景地图,包含了游戏元素精灵,当游戏中的精灵之间发生碰撞时,比如马里奥撞上砖头这种事情发生时,马里奥对象本身不知道怎么处理这个逻辑...

《Unity3D 游戏开发》宣雨松

  • 2017年12月07日 13:41
  • 27.79MB
  • 下载
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Unity3D游戏开发框架-消息机制
举报原因:
原因补充:

(最多只允许输入30个字)