Unity-基于委托消息收发机制

4 篇文章 0 订阅

在之前的博客中曾经写过一篇《Unity-基于面向对象多态特征的消息收发机制》,但是继承的层次比较多,不便于初学者的学习和使用,此篇博客是基于委托的消息收发机制。

制定事件码
事件码要对应于后面的不同的方法 事件码和方法是一一对应的 不能重复 是执行的方法的唯一标识 相当于方法的身份证

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 对于不同的模块儿使用了不同段的数字  便于管理和操作
/// </summary>
public class EventCode
{
    /// <summary>
    /// UI
    /// </summary>
    public const int UI_StartPanelActive = 10000;


    /// <summary>
    /// Net
    /// </summary>
    public const int Net_Send = 20000;
}

消息中心
消息中心作用是对事件的注册 执行和移除的处理

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MessageCenter : MonoBehaviour {

    public static MessageCenter Instance;
    /// <summary>
    /// 用于储存事件码和
    /// </summary>
    private Dictionary<int, Action<object>> messageCenterDict = new Dictionary<int, Action<object>>();
    private void Awake()
    {
        Instance = this;
    }

    public void Dispatcher(int eventCode,object message)
    {
        if (messageCenterDict.ContainsKey(eventCode))
        {
            messageCenterDict[eventCode].Invoke(message);
        }
    }

    /// <summary>
    /// 注册事件
    /// </summary>
    public void AddListener(int eventCode, Action<object> action)
    {
        if (!messageCenterDict.ContainsKey(eventCode))
        {
            messageCenterDict.Add(eventCode, action);
        }
    }
    /// <summary>
    /// 移除监听事件
    /// </summary>
    /// <param name="subcode"></param>
    public void RemoveAddlistener(int eventCode)
    {
        if (messageCenterDict.ContainsKey(eventCode))
        {
            messageCenterDict.Remove(eventCode);
        }
    }
}

测试代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class UIButton : MonoBehaviour {

	// Use this for initialization
	void Start () {
        //注册开始面板的状态的事件
        MessageCenter.Instance.AddListener(EventCode.UI_StartPanelActive, Test);
	}
    public void Test(object num)
    {
        //这里通过打印数字来展示功能  没有真的操作开始面板  Demo中也没有开始面板
        Debug.Log((int)num);
    }

    private void OnDestroy()
    {
        //取消对开始面板的监听
        MessageCenter.Instance.RemoveAddlistener(EventCode.UI_StartPanelActive);
    }
}

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RoomButton : MonoBehaviour {

	// Use this for initialization
	void Start () {
		
	}
	
	// Update is called once per frame
	void Update () {
        //触发事件
        //模式操作开始面板
        if (Input.GetMouseButtonDown(0))
        {
            MessageCenter.Instance.Dispatcher(EventCode.UI_StartPanelActive, 2);
        }
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yy763496668

您的鼓励是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值