- Home /
OnDisable calls singleton instance, creates unwanted object + errors
So I'm just having one of those mornings, not quite grasping the best way around this.
My singleton instance invokes events to which other things subscribe. Subscribers subscribe to those events through the singleton's instance.
When I exit play mode, my subscribers call their OnDisable methods to unsubscribe, but evidently the singleton instance has already been destroyed by this point, so a new instance is created.
I figured I'd just add a DontSave hideflag to the singleton instance when it is lazy-created, but the object persists once play mode has been exited. Therefor I end up with errors immediately (before playmode has fully exited) because of null references, and must delete the unwanted instance from the scene.
I know there's gotta be a clever way I can still use this design pattern, but I'm not caffeinated enough to see it. Any suggestions would be great!
ps: my singletons are monobehaviors to conveniently expose them to the inspector
Why can't you just check whether this singleton is null in OnDisable method of the subscriber when trying to unsubscribe to avoid such errors?
Thanks for the input, detailed comment on @Harshad$$anonymous$$ 's answer. :)
Answer by HarshadK · Sep 25, 2014 at 01:44 PM
Without code it is just hard to provide proper solution but you can check from your subscribers if your singleton is present or not and if it is not present then it does not need to call the unsubscribe itself since it is just gonna be useless.
Thanks for posting! $$anonymous$$y singleton classes derive from a base which automatically creates an instance if none is found in the scene. (So even checking for null will create the object and return a reference.)
For the time being I've got a second type which eschews this behavior. I'm doing as you suggest and that works out fine. Just feels messier, I guess.
I was mostly curious to learn how to avoid this problem without ditching the original lazy-instantiated singleton code.