Enhancement: Support DontDestroyOnLoad for Child GameObjects #18
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.
Description:
Currently, the UnitySingleton implementation does not persist singleton instances across scene loads when they are children of other GameObjects. This limitation arises because
DontDestroyOnLoadonly works for root GameObjects; it does not prevent destruction of child objects when their parent is destroyed during a scene load.Proposed Solution:
Introduce a public boolean property,
UnparentOnAwake, to the Singleton class. When set totrue, this property will unparent the singleton GameObject during theOnInitializingmethod, ensuring it becomes a root GameObject and is not destroyed during scene transitions.Implementation:
Use Case:
In the video "Project Initialization - Unity Architecture," Tarodev, recommends using a preload scene to initialize all the systems your game uses, such as GameManager, SoundManager, etc. The suggested approach includes the following code:
This code aims to load a single prefab named "Systems" that contains child GameObjects handling various behaviors. However, with the current UnitySingleton implementation, if these child GameObjects are singletons, they cannot persist across scenes because
DontDestroyOnLoaddoes not work on child objects. By implementing the proposedUnparentOnAwakeproperty, each system can be its own prefab, set as a child of the "Systems" GameObject, and still persist across scene loads.Benefits:
UnparentOnAwakeproperty.