Edit
In response to @Philipp answer, I thought I'd add a little additional context here.
The reason for using the StateCache and populating through OnDestroy() came from trying to retain state cross-scene. In the project (linked above), I have Scene1 and Scene2, which both have a player that moves around the screen. When I switch to MenuScene (which has no player), I need to capture the current state of the player. The reason for this is so that when I resume the previous scene (essentially simulating somewhat of a pause/resume), the game is able to restore the player to the position it held before the scene switched.
I then decided to persist the data in the StateCache on save, as I already had a mechanism built-in to be able to read/write from/to the cache from individual objects. When saving, though, I recognised that there may be some objects that haven't been destroyed and therefore wouldn't exist in the cache. As such, I create a union set from the cache and active implementors of IPreserveState in the current scene, which I find using:
FindObjectsOfType<MonoBehaviour>()
.OfType<IPreserveState>();
I guess there are maybe 2 additional questions to ask here:
- Is there a better way of preserving the state of objects (such as the player's position) between scenes without the use of the
Awake()andOnDestroy()lifecycle events? - Should I be detaching the persistence and pre-population of the
StateCachewhen saving/loading?
For reference, I have explored a number of alternative approaches, such as the singleton pattern (without DI), PlayerPrefs, etc. I found this answer, which details each of the other approaches.
