需要实现功能
降低脚本之间的耦合度
一个脚本发送数据,另一个脚本接收数据
知识点
Dictionary
(字典)的应用
Action<T>
(委托)的应用
简单的观察者模式
完整代码
using System;
using System.Collections.Generic;
using UnityEngine;
public class SimpleMsgMechanism
{
private static Dictionary<string, Action<object[]>> msgDic = new Dictionary<string, Action<object[]>>();
public static void ReceiveMsg(string msgName, Action<object[]> onMsg)
{
if (!msgDic.ContainsKey(msgName))
{
msgDic.Add(msgName, onMsg);
}
}
public static void SendMsg(string msgName, params object[] data)
{
if (msgDic.ContainsKey(msgName))
{
msgDic[msgName]?.Invoke(data);
}
}
public void ClearAllMsg()
{
msgDic.Clear();
}
}