using QSB.Messaging; using QSB.TransformSync; using QSB.Utility; namespace QSB.Events { /// /// Abstract class that handles all event code. /// /// The message type to use. public abstract class QSBEvent where T : PlayerMessage, new() { public abstract MessageType Type { get; } public uint LocalPlayerId => PlayerRegistry.LocalPlayer.NetId; private readonly MessageHandler _eventHandler; protected QSBEvent() { _eventHandler = new MessageHandler(Type); _eventHandler.OnClientReceiveMessage += OnClientReceive; _eventHandler.OnServerReceiveMessage += OnServerReceive; SetupListener(); } /// /// Called to set up the activators for the event. /// public abstract void SetupListener(); /// /// Called to remove all set up activators. /// public abstract void CloseListener(); /// /// Called on every client that didn't send the event. /// /// public virtual void OnReceiveRemote(T message) { } /// /// Called on the client that sent the event. /// /// public virtual void OnReceiveLocal(T message) { } /// /// Called on the server. /// /// public virtual void OnServerReceive(T message) { DebugLog.ToConsole("server get message"); _eventHandler.SendToAll(message); } public void SendEvent(T message) { DebugLog.ToConsole("Starting wait to send event..."); UnityHelper.Instance.RunWhen(() => PlayerTransformSync.LocalInstance != null, () => Send(message)); } private void Send(T message) { DebugLog.ToConsole("sending event!"); _eventHandler.SendToServer(message); } private void OnClientReceive(T message) { DebugLog.ToConsole("Got event!"); if (PlayerRegistry.IsBelongingToLocalPlayer(message.SenderId)) { OnReceiveLocal(message); return; } OnReceiveRemote(message); } } }