消息中心-泛型单利C#

文章介绍了在Unity3D中使用C#实现的消息中心类MessageManager,作为事件和动作的转发中心。MessageManager采用泛型单例模式,支持添加、移除和发送消息。同时展示了如何在AnimMgr组件中订阅和处理消息,用于控制角色动画播放。
摘要由CSDN通过智能技术生成

消息中心是消息的转发派发的中转站 话不多说上代码

消息中心是泛型单利的代码  如果不想搞单利 用静态效果一样自己玩完全够用的

using System;
using System.Collections.Generic;

public class MessageManager :Single<MessageManager>
{
    Dictionary<int,Action<object>> dic=new Dictionary<int,Action<object>>();
    public void Add(int id, Action<object> action)
    {
        if(dic.ContainsKey(id))
        {
            dic[id] += action;
        }
        else
        {
            dic.Add(id, action);
        }
    }
    public void Remove(int id,Action<object> action)
    {
        if (dic.ContainsKey(id))
        {
            dic[id] -= action;
            if (dic[id] == null)
            {
                dic.Remove(id);
            }
        }
    }
    public void Send(int id, params object[] arr)
    {
        if(dic.ContainsKey(id))
        {
            dic[id](arr);
        }
    }
}

单利本来不想发的因为之前发过  但是想了想还是发了吧 

上代码

public class Single<T> where T : class, new()
{
    private static T _instance;
    public static T Instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = new T();
            }
            return _instance;
        }
    }
}

怎么用也发一下吧  哎  主要就是发送和转发  

using UnityEngine;
using UnityEngine.UI;

public class AnimMgr : MonoBehaviour
{
    RuntimeAnimatorController runtimeAnimator;
    public Button button;
    void Start()
    {
        
        MessageManager.Instance.Add(1001, Skill);
        button.onClick.AddListener(() =>
        {
            MessageManager.Instance.Send(1001, 0);
        });
    }

    private void Skill(object obj)
    {
  
        object[] arr=obj as object[];
        int skillid = (int)arr[0];
        string path = SkillMgr.Instance.skillDic[skillid].animpath;
        SetAnim(path);
    }
    private void SetAnim(string path)
    {
        AnimationClip clip = Resources.Load<AnimationClip>(path);
        AnimatorOverrideController animatorOverrideController = new AnimatorOverrideController();
        animatorOverrideController.runtimeAnimatorController = runtimeAnimator;
        animatorOverrideController["Default"] = clip;
        GetComponent<Animator>().runtimeAnimatorController = null;
        GetComponent<Animator>().runtimeAnimatorController = animatorOverrideController;
        GetComponent<Animator>().Play("Default");
        //float time = clip.length;
        //overrideController["Take 002"] = clip;
        //animator.SetBool("Play", true);

    }
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值