I have different persistent singletons in the scene, one of which references the others on the OnValidate method.
But, when it does so, the others have not been initialized yet. So, as per implementation of the Instance property, this causes the instantiation of other Singletons, but the previous ones don’t get deleted (luckily!) because all this happens at Edit time.
I tried to declare the OnValidate as IEnumerable so that I was able to do a few yields to delay everything of 2 frames, but it’s forbidden.
I still want to keep the OnValidate functionality, but I want it to fire only after the whole scene gets instantiated - and I’m surprised because all this happens before the Awake call of the other singletons.
This also only happens when loading Unity the first time. A few objects along with the new singletons get created, there is some nullreferencing going on, but reloading the scene works just as fine.
How would you handle such situation? Is there any way to catch the moment when all the objects are actually initialized? Should I call the onvalidate manually from the Awake method of other singletons, or maybe I should use a flag to delay the OnValidate call only when every Awake method has been called?
That being said - your rat’s nest of inter-dependent singletons that spawn other singletons sounds absolutely terrifying and it’s not surprising that you’ve run into maintainability problems
Lol, I know. I’m not really spawning singletons from singletons, but each singleton by default will spawn an appropriate singleton if not available whenever it gets referred with Instance. And this could happen in other singletons (The Gamemanager that initializes the levelmanager and other stuff)
Unfortunately I’m using different asset store assets for different purposes, and each own has its own set of managers, some persistent, other not. And I also have to define mines, since they’re very game specific and I’d need multiple inheritance.
I solved everything by choosing a “master” singleton which notifies the other singletons when to initialize their behaviour on scene full loading/before unloading.
When a Validate occurs before the initialization, the behaviour sets its “pendingValidate” to true. Whenever the scene gets initialized, if there’s a pending Validate, it gets called.
I need to hook the change of a variable in a native Unity class (that doesn’t provide any event or hook) so it gets instantly reflected on the property of another Singleton that stores the current variable for the scene. The values from the unity class and the ones from the Singleton are sort of linked together in both directions.