55 lines
1.3 KiB
C#
55 lines
1.3 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using Google.Protobuf;
|
|
using UnityEngine;
|
|
|
|
public class SocketMessageManager : MonoBehaviour
|
|
{
|
|
// 使用字典存储
|
|
private Dictionary<MessageID, Action<ByteString>> _eventDictionary;
|
|
|
|
public static SocketMessageManager Instance { get; private set; }
|
|
|
|
private void Awake()
|
|
{
|
|
if (Instance != null)
|
|
{
|
|
Destroy(gameObject);
|
|
return;
|
|
}
|
|
|
|
Instance = this;
|
|
_eventDictionary = new Dictionary<MessageID, Action<ByteString>>();
|
|
}
|
|
|
|
// 订阅事件
|
|
public void Subscribe(MessageID messageID, Action<ByteString> listener)
|
|
{
|
|
if (_eventDictionary.ContainsKey(messageID))
|
|
{
|
|
_eventDictionary[messageID] += listener;
|
|
}
|
|
else
|
|
{
|
|
_eventDictionary[messageID] = listener;
|
|
}
|
|
}
|
|
|
|
// 取消订阅
|
|
public void Unsubscribe(MessageID messageID, Action<ByteString> listener)
|
|
{
|
|
if (_eventDictionary.ContainsKey(messageID))
|
|
{
|
|
_eventDictionary[messageID] -= listener;
|
|
}
|
|
}
|
|
|
|
// 触发事件
|
|
public void TriggerEvent(MessageID messageID, ByteString data = null)
|
|
{
|
|
if (_eventDictionary.ContainsKey(messageID))
|
|
{
|
|
_eventDictionary[messageID]?.Invoke(data);
|
|
}
|
|
}
|
|
} |