Joining a server after v1.4.0 threw "An item with the same key has already been added" in ObjectDB.UpdateRegisters and bounced the player back to the start menu. Rather than guess the exact colliding prefab offline, this strips any duplicate-hash entries from m_items right before the vanilla rebuild runs and logs their names, so the join no longer crashes and the log now names the actual offender. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
55 lines
2.2 KiB
C#
55 lines
2.2 KiB
C#
using System.Collections.Generic;
|
|
using HarmonyLib;
|
|
using UnityEngine;
|
|
|
|
namespace RacesOfValheim
|
|
{
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
[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<int>();
|
|
var deduped = new List<GameObject>(__instance.m_items.Count);
|
|
var droppedNames = new List<string>();
|
|
|
|
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.");
|
|
}
|
|
}
|
|
}
|
|
}
|