using QSB.Messaging; using QSB.TransformSync; using UnityEngine.Networking; namespace QSB.Events { /// /// Abstract class that handles all event code. /// /// The message type to use. public abstract class QSBEvent : IQSBEvent where T : PlayerMessage, new() { public abstract EventType Type { get; } public uint LocalPlayerId => PlayerRegistry.LocalPlayerId; private readonly MessageHandler _eventHandler; protected QSBEvent() { _eventHandler = new MessageHandler(Type); _eventHandler.OnClientReceiveMessage += OnClientReceive; _eventHandler.OnServerReceiveMessage += OnServerReceive; } /// /// 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) { _eventHandler.SendToAll(message); } public void SendEvent(T message) { message.FromId = PlayerRegistry.LocalPlayerId; QSB.Helper.Events.Unity.RunWhen(() => PlayerTransformSync.LocalInstance != null, () => Send(message)); } private void Send(T message) { if (NetworkServer.active) { _eventHandler.SendToAll(message); } else { _eventHandler.SendToServer(message); } } private void OnClientReceive(T message) { if (message.FromId == PlayerRegistry.LocalPlayerId || PlayerRegistry.IsBelongingToLocalPlayer(message.AboutId)) { OnReceiveLocal(message); return; } OnReceiveRemote(message); } } }