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

54 lines
1.7 KiB
C#
Raw Normal View History

2020-08-09 11:19:51 +00:00
using QSB.Messaging;
using QSB.Utility;
using System.Linq;
using UnityEngine;
using UnityEngine.Networking;
namespace QSB.Events
{
2020-08-10 16:17:54 +00:00
public class PlayerLeaveEvent : QSBEvent<PlayerLeaveMessage>
2020-08-09 11:19:51 +00:00
{
public override MessageType Type => MessageType.PlayerLeave;
public override void SetupListener()
{
2020-08-10 17:24:28 +00:00
GlobalMessenger<uint, uint[]>.AddListener(EventNames.QSBPlayerLeave, (id, objects) => SendEvent(CreateMessage(id, objects)));
2020-08-09 11:19:51 +00:00
}
2020-08-10 16:17:54 +00:00
private PlayerLeaveMessage CreateMessage(uint id, uint[] objects) => new PlayerLeaveMessage
{
SenderId = id,
ObjectIds = objects
};
2020-08-10 13:40:06 +00:00
public override void OnReceiveRemote(PlayerLeaveMessage message)
2020-08-09 11:19:51 +00:00
{
var playerName = PlayerRegistry.GetPlayer(message.SenderId).Name;
DebugLog.ToAll(playerName, "disconnected.");
PlayerRegistry.RemovePlayer(message.SenderId);
foreach (var objectId in message.ObjectIds)
{
DestroyObject(objectId);
}
}
2020-08-13 17:27:12 +00:00
public override void OnReceiveLocal(PlayerLeaveMessage message) => OnReceiveRemote(message);
2020-08-13 16:44:27 +00:00
2020-08-09 11:19:51 +00:00
private void DestroyObject(uint objectId)
{
var component = Object.FindObjectsOfType<NetworkBehaviour>()
.FirstOrDefault(x => x.netId.Value == objectId);
if (component == null)
{
return;
}
var transformSync = component.GetComponent<TransformSync.TransformSync>();
if (transformSync != null)
{
Object.Destroy(transformSync.SyncedTransform.gameObject);
}
Object.Destroy(component.gameObject);
}
}
}