quantum-space-buddies/QSB/TransformSync/PlayerSectorEvent.cs
2020-09-02 11:17:04 +01:00

54 lines
1.7 KiB
C#

using OWML.Common;
using QSB.Events;
using QSB.Messaging;
using QSB.Utility;
using QSB.WorldSync;
using UnityEngine.Networking;
namespace QSB.TransformSync
{
public class PlayerSectorEvent : QSBEvent<WorldObjectMessage>
{
public override EventType Type => EventType.PlayerSectorChange;
public override void SetupListener()
{
GlobalMessenger<NetworkInstanceId, QSBSector>.AddListener(EventNames.QSBSectorChange, Handler);
}
public override void CloseListener()
{
GlobalMessenger<NetworkInstanceId, QSBSector>.RemoveListener(EventNames.QSBSectorChange, Handler);
}
private void Handler(NetworkInstanceId netId, QSBSector sector) => SendEvent(CreateMessage(netId, sector));
private WorldObjectMessage CreateMessage(NetworkInstanceId netId, QSBSector sector) => new WorldObjectMessage
{
AboutId = netId,
ObjectId = sector.ObjectId
};
public override void OnReceiveRemote(WorldObjectMessage message)
{
if (!QSBSceneManager.IsInUniverse)
{
return;
}
var sector = WorldRegistry.GetObject<QSBSector>(message.ObjectId);
if (sector == null)
{
DebugLog.ToConsole($"Sector with order id {message.ObjectId} not found!", MessageType.Warning);
return;
}
var transformSync = PlayerRegistry.GetSyncObject<TransformSync>(message.AboutId);
QSB.Helper.Events.Unity.RunWhen(() => transformSync.SyncedTransform != null,
() => transformSync.SetReferenceSector(sector));
}
}
}