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-10 11:45:24 +01:00
_eventHandler.OnClientReceiveMessage += OnClientReceive;
_eventHandler.OnServerReceiveMessage += OnServerReceive;
2020-08-09 09:17:00 +02:00
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-10 11:45:24 +01:00
public virtual void OnServerReceive(T message)
2020-08-09 09:17:00 +02:00
{
_eventHandler.SendToAll(message);
}
2020-08-10 11:45:24 +01:00
private void OnClientReceive(T message)
2020-08-09 09:17:00 +02:00
{
2020-08-09 14:26:33 +01:00
if (message.SenderId == PlayerTransformSync.LocalInstance?.netId.Value)
2020-08-09 09:17:00 +02:00
{
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
}
}
}