quantum-space-buddies/QSB/Events/QSBEvent.cs

79 lines
2.2 KiB
C#
Raw Normal View History

2020-08-08 12:27:49 +00:00
using QSB.Messaging;
2020-08-09 07:17:00 +00:00
using QSB.TransformSync;
using QSB.Utility;
namespace QSB.Events
{
2020-08-10 13:48:40 +00:00
/// <summary>
/// Abstract class that handles all event code.
/// </summary>
/// <typeparam name="T">The message type to use.</typeparam>
2020-08-09 07:37:32 +00:00
public abstract class QSBEvent<T> where T : PlayerMessage, new()
{
2020-08-09 07:17:00 +00:00
public abstract MessageType Type { get; }
2020-08-10 13:40:06 +00:00
public uint LocalPlayerId => PlayerRegistry.LocalPlayer.NetId;
2020-08-10 13:48:40 +00:00
private readonly MessageHandler<T> _eventHandler;
protected QSBEvent()
{
_eventHandler = new MessageHandler<T>(Type);
_eventHandler.OnClientReceiveMessage += OnClientReceive;
_eventHandler.OnServerReceiveMessage += OnServerReceive;
SetupListener();
}
2020-08-10 13:40:06 +00:00
2020-08-10 13:48:40 +00:00
/// <summary>
/// Called to set up the activators for the event.
/// </summary>
2020-08-08 11:23:23 +00:00
public abstract void SetupListener();
2020-08-10 13:48:40 +00:00
/// <summary>
/// Called on every client that didn't send the event.
/// </summary>
/// <param name="message"></param>
2020-08-10 13:40:06 +00:00
public virtual void OnReceiveRemote(T message)
{
}
2020-08-09 07:17:00 +00:00
2020-08-10 13:48:40 +00:00
/// <summary>
/// Called on the client that sent the event.
/// </summary>
/// <param name="message"></param>
2020-08-09 07:37:32 +00:00
public virtual void OnReceiveLocal(T message)
2020-08-09 07:17:00 +00:00
{
2020-08-10 13:40:06 +00:00
OnReceiveRemote(message);
2020-08-09 07:17:00 +00:00
}
2020-08-10 13:48:40 +00:00
/// <summary>
/// Called on the server.
/// </summary>
/// <param name="message"></param>
public virtual void OnServerReceive(T message)
2020-08-09 07:37:32 +00:00
{
2020-08-10 13:48:40 +00:00
_eventHandler.SendToAll(message);
2020-08-09 07:37:32 +00:00
}
2020-08-10 13:48:40 +00:00
public void SendEvent(T message)
2020-08-09 07:17:00 +00:00
{
2020-08-10 13:48:40 +00:00
UnityHelper.Instance.RunWhen(() => PlayerTransformSync.LocalInstance != null, () => Send(message));
2020-08-09 07:17:00 +00:00
}
2020-08-09 07:37:32 +00:00
private void Send(T message)
2020-08-09 07:17:00 +00:00
{
2020-08-09 07:37:32 +00:00
_eventHandler.SendToServer(message);
2020-08-09 07:17:00 +00:00
}
2020-08-10 10:45:24 +00:00
private void OnClientReceive(T message)
2020-08-09 07:17:00 +00:00
{
2020-08-09 13:26:33 +00:00
if (message.SenderId == PlayerTransformSync.LocalInstance?.netId.Value)
2020-08-09 07:17:00 +00:00
{
2020-08-09 11:19:51 +00:00
OnReceiveLocal(message);
2020-08-09 07:17:00 +00:00
return;
}
2020-08-09 07:37:32 +00:00
2020-08-10 13:40:06 +00:00
OnReceiveRemote(message);
2020-08-09 07:17:00 +00:00
}
}
}