考虑在unity中做一个事件系统 当接收到消息的时候传入参数自动调用

感觉设计上有很大的问题 特别是每次参数还要转换两次类型  但又不知道具体改如何赶紧 求教 大神们给点意见 

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



public delegate System.Object FuncPoint1(params object[] objAry);        //可变参的委托
public delegate void FuncPoint(params object[] objAry);

public class Observe_0
{
    private static Observe_0 _instance;

    public static Observe_0 Instance {                        //制作一个单例尝试在全局中使用
        get => _instance = _instance ?? new Observe_0();
        set => _instance = value;
    }


    private static Dictionary<string, FuncPoint>
        funcDic = new Dictionary<string, FuncPoint>();


    public void ListenEvent<T>(FuncPoint fp)                    //根据消息的类型将对应的处理方法加入字典 (考虑服务器发送的通用消息   可以在弄个枚举针对性处理)
    {
        string className = typeof(T).ToString();
        funcDic[className] = fp;
    }
    public void Execute<T>(params object[] objAry) {
        if (funcDic.ContainsKey(typeof(T).ToString()))
            funcDic[typeof(T).ToString()].Invoke(objAry);
    }

}

public class C2S_DownImage{
    public string name = "yc大菜鸡";
}

public class Observe : MonoBehaviour {
    
    

    private void Start()
    {
        Observe_0.Instance.ListenEvent<C2S_DownImage>(print111);

        Observe_0.Instance.Execute<C2S_DownImage>("asdasdsadasd");


        Observe_0.Instance.ListenEvent<C2S_DownImage>(print1);
        Observe_0.Instance.Execute<C2S_DownImage>("asdsad", "asdsadsadsadsadsadsadsa",new C2S_DownImage());


    }

    public void print111(object message) {
        print(message + "            1111111");
    }



    public void print1(params object[] name1) {
        print(name[0]);
        print(name[1]);
        var t = name1[2] as C2S_DownImage;
        print(t.name);

    }


}

  

上一篇:区块链学习(3)


下一篇:各种内部类的写法