Fix: Release() call during SoftReference location registration causes intermittent NullReferenceException#464
Merged
MSchmoecker merged 1 commit intoValheim-Modding:devfrom Dec 29, 2025
Conversation
Member
|
Thanks, good catch on this edge case |
MSchmoecker
approved these changes
Dec 29, 2025
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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.