feat: Enhance BuildingRemove logic to correctly manage Player.inst during building removal

This commit is contained in:
2025-12-15 09:22:50 +01:00
parent 7d06145a34
commit 46ebeb1f80
2 changed files with 44 additions and 1 deletions

32
Main.cs
View File

@@ -1018,6 +1018,9 @@ namespace KCM
[HarmonyPatch(typeof(Building), "Remove")] [HarmonyPatch(typeof(Building), "Remove")]
public class BuildingRemoveHook public class BuildingRemoveHook
{ {
// Store original Player.inst to restore after Remove
private static Player originalPlayerInst = null;
public static void Prefix(Building __instance) public static void Prefix(Building __instance)
{ {
try try
@@ -1038,11 +1041,38 @@ namespace KCM
guid = __instance.guid guid = __instance.guid
}.Send(); }.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) 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); helper.Log(e.StackTrace);
} }
} }

View File

@@ -42,7 +42,20 @@ namespace KCM.Packets.Game.GameBuilding
// Set flag to prevent sending packet back // Set flag to prevent sending packet back
isProcessingPacket = true; 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(); building.Remove();
// Restore original Player.inst
Player.inst = originalPlayer;
isProcessingPacket = false; isProcessingPacket = false;
} }
catch (Exception e) catch (Exception e)