using QSB.Messaging; using QSB.Utility; using System.Linq; using UnityEngine; using UnityEngine.Networking; namespace QSB.Events { public class PlayerLeaveEvent : QSBEvent { public override MessageType Type => MessageType.PlayerLeave; public override void SetupListener() { GlobalMessenger.AddListener(EventNames.QSBPlayerLeave, (id, objects) => SendEvent(CreateMessage(id, objects))); } private PlayerLeaveMessage CreateMessage(uint id, uint[] objects) => new PlayerLeaveMessage { SenderId = id, ObjectIds = objects }; public override void OnReceiveRemote(PlayerLeaveMessage message) { var playerName = PlayerRegistry.GetPlayer(message.SenderId).Name; DebugLog.ToAll(playerName, "disconnected."); PlayerRegistry.RemovePlayer(message.SenderId); foreach (var objectId in message.ObjectIds) { DestroyObject(objectId); } } public override void OnReceiveLocal(PlayerLeaveMessage message) => OnReceiveRemote(message); private void DestroyObject(uint objectId) { var component = Object.FindObjectsOfType() .FirstOrDefault(x => x.netId.Value == objectId); if (component == null) { return; } var transformSync = component.GetComponent(); if (transformSync != null) { Object.Destroy(transformSync.SyncedTransform.gameObject); } Object.Destroy(component.gameObject); } } }