Skip to content

Fix: Release() call during SoftReference location registration causes intermittent NullReferenceException#464

Merged
MSchmoecker merged 1 commit intoValheim-Modding:devfrom
jneb802:dev
Dec 29, 2025
Merged

Fix: Release() call during SoftReference location registration causes intermittent NullReferenceException#464
MSchmoecker merged 1 commit intoValheim-Modding:devfrom
jneb802:dev

Conversation

@jneb802
Copy link
Contributor

@jneb802 jneb802 commented Dec 23, 2025

The SoftReference system uses reference counting to manage asset memory - Load() increments the count, Release() decrements it, and when the count reaches zero the asset is unloaded.

When registering SoftReference locations in ZoneManager.cs, PrepareLocation() is skipped (which normally calls Load), but RegisterLocationInZoneSystem() still calls Release(). This causes the reference count to underflow from 0 to uint.MaxValue (since it's unsigned). While the underflow itself doesn't trigger unloading (uint.MaxValue is not <= 0), it causes the count to be off by one for all subsequent operations.

The problem manifests when a location receives multiple Load calls during gameplay (async load from ZoneSystem.LocationPrefabLoadData + sync load from ZoneSystem.SpawnLocation). With the count off by one, releases bring it back to zero one call early, unloading the asset while it's still being accessed elsewhere. This causes intermittent NullReferenceExceptions in ZoneSystem.SpawnLocation when accessing location.m_prefab.Asset.

The fix is to only call Release() in RegisterLocationInZoneSystem() if the prefab was actually loaded during preparation, keeping the reference count balanced from the start.

@MSchmoecker
Copy link
Member

Thanks, good catch on this edge case

@MSchmoecker MSchmoecker disabled auto-merge December 29, 2025 08:14
@MSchmoecker MSchmoecker merged commit 016cbbe into Valheim-Modding:dev Dec 29, 2025
1 check failed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants