From 46ebeb1f804146fc92375b0c9ba61f66cb91481e Mon Sep 17 00:00:00 2001 From: b3ni15 Date: Mon, 15 Dec 2025 09:22:50 +0100 Subject: [PATCH] feat: Enhance BuildingRemove logic to correctly manage Player.inst during building removal --- Main.cs | 32 ++++++++++++++++++- .../Game/GameBuilding/BuildingRemovePacket.cs | 13 ++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) diff --git a/Main.cs b/Main.cs index a21f99c..4881c91 100644 --- a/Main.cs +++ b/Main.cs @@ -1018,6 +1018,9 @@ namespace KCM [HarmonyPatch(typeof(Building), "Remove")] public class BuildingRemoveHook { + // Store original Player.inst to restore after Remove + private static Player originalPlayerInst = null; + public static void Prefix(Building __instance) { try @@ -1038,11 +1041,38 @@ namespace KCM guid = __instance.guid }.Send(); } + + // Set Player.inst to the correct player for this building + // This ensures Remove() modifies the correct player's job lists + originalPlayerInst = Player.inst; + Player correctPlayer = GetPlayerByBuilding(__instance); + if (correctPlayer != null && correctPlayer != Player.inst) + { + Player.inst = correctPlayer; + } } } catch (Exception e) { - helper.Log($"Error in BuildingRemoveHook: {e.Message}"); + helper.Log($"Error in BuildingRemoveHook Prefix: {e.Message}"); + helper.Log(e.StackTrace); + } + } + + public static void Postfix(Building __instance) + { + try + { + // Restore original Player.inst after Remove completes + if (KCClient.client.IsConnected && originalPlayerInst != null) + { + Player.inst = originalPlayerInst; + originalPlayerInst = null; + } + } + catch (Exception e) + { + helper.Log($"Error in BuildingRemoveHook Postfix: {e.Message}"); helper.Log(e.StackTrace); } } diff --git a/Packets/Game/GameBuilding/BuildingRemovePacket.cs b/Packets/Game/GameBuilding/BuildingRemovePacket.cs index 1020332..53738e2 100644 --- a/Packets/Game/GameBuilding/BuildingRemovePacket.cs +++ b/Packets/Game/GameBuilding/BuildingRemovePacket.cs @@ -42,7 +42,20 @@ namespace KCM.Packets.Game.GameBuilding // Set flag to prevent sending packet back isProcessingPacket = true; + + // Set Player.inst to the correct player for this building + // This ensures Remove() modifies the correct player's job lists + Player originalPlayer = Player.inst; + Player correctPlayer = Main.GetPlayerByBuilding(building); + if (correctPlayer != null) + { + Player.inst = correctPlayer; + } + building.Remove(); + + // Restore original Player.inst + Player.inst = originalPlayer; isProcessingPacket = false; } catch (Exception e)