diff --git a/JotunnModStub/ObjectDBDedupePatch.cs b/JotunnModStub/ObjectDBDedupePatch.cs new file mode 100644 index 0000000..b8d1e45 --- /dev/null +++ b/JotunnModStub/ObjectDBDedupePatch.cs @@ -0,0 +1,55 @@ +using System.Collections.Generic; +using HarmonyLib; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// Diagnostic/safety net for "An item with the same key has already been added" in + /// ObjectDB.UpdateRegisters, seen when joining a server after v1.4.0 (worked in 1.3.11). + /// UpdateRegisters rebuilds m_itemByHash from m_items with a plain Dictionary.Add, so it + /// crashes the instant two entries in m_items share a name hash - most likely two GameObjects + /// with the exact same .name, from some mod-registered item ending up in the list twice + /// across a reconnect. Rather than guess the exact prefab from a hash offline, this strips + /// duplicates before the vanilla method runs and logs every name it had to drop, so the next + /// crash-free join tells us precisely which prefab is being double-registered. + /// + [HarmonyPatch(typeof(ObjectDB), "UpdateRegisters")] + public static class ObjectDB_UpdateRegisters_DedupePatch + { + public static void Prefix(ObjectDB __instance) + { + if (__instance == null || __instance.m_items == null) return; + + var seen = new HashSet(); + var deduped = new List(__instance.m_items.Count); + var droppedNames = new List(); + + foreach (GameObject item in __instance.m_items) + { + if (item == null) continue; + + int hash = item.name.GetStableHashCode(); + if (seen.Add(hash)) + { + deduped.Add(item); + } + else + { + droppedNames.Add(item.name); + } + } + + if (droppedNames.Count > 0) + { + __instance.m_items.Clear(); + __instance.m_items.AddRange(deduped); + + Jotunn.Logger.LogWarning( + $"[RacesOfValheim] ObjectDB.m_items had {droppedNames.Count} duplicate-hash entr" + + (droppedNames.Count == 1 ? "y" : "ies") + + $" before UpdateRegisters: {string.Join(", ", droppedNames)}. Dropped the repeats to avoid the crash."); + } + } + } +}