58 lines
1.4 KiB
C#
Raw Normal View History

2020-08-08 13:27:49 +01:00
using QSB.Messaging;
2020-08-09 09:17:00 +02:00
using QSB.TransformSync;
using QSB.Utility;
namespace QSB.Events
{
2020-08-09 09:37:32 +02:00
public abstract class QSBEvent<T> where T : PlayerMessage, new()
{
2020-08-09 09:17:00 +02:00
public abstract MessageType Type { get; }
2020-08-08 12:23:23 +01:00
public abstract void SetupListener();
2020-08-09 12:19:51 +01:00
public abstract void OnReceive(T message);
2020-08-09 09:17:00 +02:00
2020-08-09 09:37:32 +02:00
public virtual void OnReceiveLocal(T message)
2020-08-09 09:17:00 +02:00
{
2020-08-09 13:58:13 +01:00
OnReceive(message);
2020-08-09 09:17:00 +02:00
}
2020-08-09 09:37:32 +02:00
public void SendEvent(T message)
{
UnityHelper.Instance.RunWhen(() => PlayerTransformSync.LocalInstance != null, () => Send(message));
}
private readonly MessageHandler<T> _eventHandler;
2020-08-09 09:17:00 +02:00
protected QSBEvent()
{
2020-08-09 09:37:32 +02:00
_eventHandler = new MessageHandler<T>(Type);
2020-08-09 09:17:00 +02:00
_eventHandler.OnClientReceiveMessage += OnClientReceiveMessage;
_eventHandler.OnServerReceiveMessage += OnServerReceiveMessage;
SetupListener();
}
2020-08-09 09:37:32 +02:00
private void Send(T message)
2020-08-09 09:17:00 +02:00
{
2020-08-09 09:37:32 +02:00
_eventHandler.SendToServer(message);
2020-08-09 09:17:00 +02:00
}
2020-08-09 09:37:32 +02:00
private void OnServerReceiveMessage(T message)
2020-08-09 09:17:00 +02:00
{
_eventHandler.SendToAll(message);
}
2020-08-09 09:37:32 +02:00
private void OnClientReceiveMessage(T message)
2020-08-09 09:17:00 +02:00
{
if (message.SenderId == PlayerRegistry.LocalPlayer?.NetId)
{
2020-08-09 12:19:51 +01:00
OnReceiveLocal(message);
2020-08-09 09:17:00 +02:00
return;
}
2020-08-09 09:37:32 +02:00
2020-08-09 12:19:51 +01:00
OnReceive(message);
2020-08-09 09:17:00 +02:00
}
}
}