Fix so that “DontDestroyOnLoad” takes precedence when there are multiple LifetimeScope of the same class. #703
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.
What happened?
When I use
FindAnyObjectByType
inLifetimeScope.Find
, the order of acquisition is not guaranteed and sometimesConfigure
is not called. Also, I am using a singleton LifetimeScope, which is a rare case, but I would appreciate your consideration.VContainer/VContainer/Assets/VContainer/Runtime/Unity/LifetimeScope.cs
Lines 118 to 125 in 583d021
Reproducing the problem
Assert
ofReloadTestLifetimeScope
fails.Code
DontDestroyOnLoadLifetimeScope.cs
singleton LifetimeScope
ReloadTestLifetimeScope.cs
a LifetimeScope with a singleton LifetimeScope as Parent
ReloadScene.cs
Scene reloading.
Problem solved
Fixed so that if multiple LifetimeScope of the same class exist, the LifetimeScope with DontDestroyOnLoad is returned. The reason is that there are no other situations where multiple LifetimeScope exist. Also, if there are no more than one, the first one in the array is returned. Internally, this is exactly the same code as the previous code.
Current
VContainer/VContainer/Assets/VContainer/Runtime/Unity/LifetimeScope.cs
Lines 118 to 125 in 583d021
After
VContainer/VContainer/Assets/VContainer/Runtime/Unity/LifetimeScope.cs
Lines 118 to 137 in 0119b2d
About performance
As explained, performance is the same as before when there is no more than one. The internal implementation of
FindAnyObjectByType
andFindObjectOfType
used is as follows.FindObjectsOfType handling
In my testing,
FindObjectOfType
was always stored in the array in the order it was created, as opposed toFindAnyObjectByType
, but since there seems to be no guarantee of order, I made the same modification to give priority to DontDestroyOnLoad The same modification has been made to prioritize DontDestroyOnLoad.