quantum-space-buddies/QSB/Events/PlayerLeave.cs
2020-08-09 11:11:45 +02:00

60 lines
1.7 KiB
C#

using System.Linq;
using QSB.Messaging;
using QSB.Utility;
using UnityEngine.Networking;
namespace QSB.Events
{
/// <summary>
/// Client-only-side component for managing player leaves.
/// </summary>
public class PlayerLeave : NetworkBehaviour
{
private MessageHandler<LeaveMessage> _leaveHandler;
private void Awake()
{
_leaveHandler = new MessageHandler<LeaveMessage>(MessageType.Leave);
_leaveHandler.OnClientReceiveMessage += OnClientReceiveMessage;
}
public void Leave(uint playerId, uint[] objectIds)
{
var message = new LeaveMessage
{
SenderId = playerId,
ObjectIds = objectIds
};
_leaveHandler.SendToAll(message);
}
private void OnClientReceiveMessage(LeaveMessage message)
{
var playerName = PlayerRegistry.GetPlayer(message.SenderId).Name;
DebugLog.ToAll(playerName, "disconnected.");
PlayerRegistry.RemovePlayer(message.SenderId);
foreach (var objectId in message.ObjectIds)
{
DestroyObject(objectId);
}
}
private void DestroyObject(uint objectId)
{
var component = FindObjectsOfType<NetworkBehaviour>()
.FirstOrDefault(x => x.netId.Value == objectId);
if (component == null)
{
return;
}
var transformSync = component.GetComponent<TransformSync.TransformSync>();
if (transformSync != null)
{
Destroy(transformSync.SyncedTransform.gameObject);
}
Destroy(component.gameObject);
}
}
}