From 256a0e350b510ba4e3a37c556a7c23ade60c81a9 Mon Sep 17 00:00:00 2001 From: JohnCorby Date: Thu, 26 May 2022 21:27:55 -0700 Subject: [PATCH] TryGetWorldObject --- QSB/ShipSync/Patches/ShipPatches.cs | 4 ++-- QSB/WorldSync/QSBWorldSync.cs | 21 +++++++++++++++++++-- 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/QSB/ShipSync/Patches/ShipPatches.cs b/QSB/ShipSync/Patches/ShipPatches.cs index 82c1a90a..e062e3c0 100644 --- a/QSB/ShipSync/Patches/ShipPatches.cs +++ b/QSB/ShipSync/Patches/ShipPatches.cs @@ -282,12 +282,12 @@ internal class ShipPatches : QSBPatch return; } - if (!__instance.HasWorldObject()) + if (!__instance.TryGetWorldObject(out QSBShipLight qsbShipLight)) { return; } - __instance.GetWorldObject().SendMessage(new ShipLightMessage(on)); + qsbShipLight.SendMessage(new ShipLightMessage(on)); } [HarmonyPrefix] diff --git a/QSB/WorldSync/QSBWorldSync.cs b/QSB/WorldSync/QSBWorldSync.cs index 5451b8a0..9c50dcb6 100644 --- a/QSB/WorldSync/QSBWorldSync.cs +++ b/QSB/WorldSync/QSBWorldSync.cs @@ -269,8 +269,25 @@ public static class QSBWorldSync return (TWorldObject)worldObject; } - public static bool HasWorldObject(this MonoBehaviour unityObject) - => unityObject && UnityObjectsToWorldObjects.ContainsKey(unityObject); + public static bool TryGetWorldObject(this MonoBehaviour unityObject, out TWorldObject worldObject) + where TWorldObject : IWorldObject + { + if (!unityObject) + { + DebugLog.ToConsole($"Error - Trying to run GetWorldFromUnity with a null unity object! TWorldObject:{typeof(TWorldObject).Name}, TUnityObject:NULL, Stacktrace:\r\n{Environment.StackTrace}", MessageType.Error); + worldObject = default; + return false; + } + + if (!UnityObjectsToWorldObjects.TryGetValue(unityObject, out var iWorldObject)) + { + worldObject = default; + return false; + } + + worldObject = (TWorldObject)iWorldObject; + return true; + } /// /// not deterministic across platforms.