quantum-space-buddies/QSB/SectorSync.cs

75 lines
2.7 KiB
C#
Raw Normal View History

2020-02-13 20:23:12 +00:00
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
2020-02-13 19:23:26 +00:00
namespace QSB {
2020-02-13 20:23:12 +00:00
public class SectorSync: MessageHandler {
protected override short type { get => MessageType.Sector; }
static Dictionary<uint, Transform> playerSectors;
static Sector[] _allSectors;
2020-02-13 20:23:12 +00:00
void Awake () {
playerSectors = new Dictionary<uint, Transform>();
_allSectors = FindObjectsOfType<Sector>();
2020-02-13 20:48:23 +00:00
QSB.Helper.HarmonyHelper.AddPrefix<PlayerSectorDetector>("OnAddSector", typeof(Patches), "PreAddSector");
2020-02-13 20:23:12 +00:00
}
2020-02-13 21:11:20 +00:00
public static void SetSector (NetworkInstanceId netId, Sector.Name sectorName, bool skipAnnounce = false) {
2020-02-13 21:18:41 +00:00
if (sectorName == Sector.Name.Unnamed || sectorName != Sector.Name.Ship && sectorName != Sector.Name.Sun) {
return;
}
playerSectors[netId.Value] = GetSectorTransform(sectorName);
2020-02-13 21:11:20 +00:00
if (!skipAnnounce) {
SectorMessage msg = new SectorMessage();
msg.sectorId = (int) sectorName;
msg.senderId = netId.Value;
NetworkManager.singleton.client.Send(MessageType.Sector, msg);
}
}
public static Transform GetSector (NetworkInstanceId netId) {
return playerSectors[netId.Value];
}
2020-02-13 21:18:41 +00:00
static Transform GetSectorTransform (Sector.Name sectorName) {
foreach (var sector in _allSectors) {
2020-02-13 20:23:12 +00:00
if (sectorName == sector.GetName()) {
return sector.transform;
}
}
return null;
}
2020-02-13 20:48:23 +00:00
protected override void OnClientReceiveMessage (NetworkMessage netMsg) {
2020-02-13 20:23:12 +00:00
SectorMessage msg = netMsg.ReadMessage<SectorMessage>();
var sectorName = (Sector.Name) msg.sectorId;
2020-02-13 21:18:41 +00:00
var sectorTransform = GetSectorTransform(sectorName);
2020-02-13 20:23:12 +00:00
if (sectorTransform == null) {
QSB.LogToScreen("Sector", sectorName, "not found");
return;
}
QSB.LogToScreen("Found sector", sectorName, ", setting for", msg.senderId);
playerSectors[msg.senderId] = sectorTransform;
}
2020-02-13 20:48:23 +00:00
protected override void OnServerReceiveMessage (NetworkMessage netMsg) {
SectorMessage msg = netMsg.ReadMessage<SectorMessage>();
NetworkServer.SendToAll(MessageType.Sector, msg);
}
static class Patches {
static void PreAddSector (Sector sector, PlayerSectorDetector __instance) {
if (NetworkPlayer.localInstance != null) {
NetworkPlayer.localInstance.EnterSector(sector);
}
}
}
2020-02-13 19:23:26 +00:00
}
}