Instantiate singleton to used by button onclick events

How can I programmatically instantiate a singleton that can be used with button onclick events in multiple scenes?

I’ve tried putting the singleton’s parent object into resources and calling instanciate, but that opens up another kettle of fish.

Also when a button’s onclick event accesses a class it doesn’t trigger the Awake method which is used to keep the singleton… single…

Any ideas… Thanks

Why not just attach the singleton class to an empty gameobject and access it when you need to?

The reason why is a chain of events, please bear with me:

  • the singleton is used to load/unload async additive composite scenes,
  • which in turn means it has a coroutine that checks to see if a scene is loaded,
  • which causes the error “Coroutine couldn’t be started because the the game object ‘GameManagerObject’ is inactive”,
  • which is because there’s more than one instance of the singleton, with the wrong one being active
  • which is because when a button’s onlick event accesses the singleton, the Awake method is not invoked which checks for duplication.

The easy fix, is to remove step 2, and just put the “wait” code into each individual scene and put up with two singletons being active. But I shouldn’t have to duplicate code everywhere in all the scenes nor have two singletons which will bite me in the arse later on for other things too.

The proper fix is to instantiate the Singleton ASAP and make sure the Button onclick events use that instance, but I can’t see how as the Button onclick event takes the Base class name, not an instance handle… also Awake is not triggered as mentioned.

I tend to use lazy instantiation for my singletons. Put the instance variable into a property. If instance doesn’t exist, then Instantiate it. Otherwise return instance.

Just do what I do.

Write your Singleton as a ScriptableObject with the [CreateAssetMenu] attribute. then create it in the project and have all your needed classes have a public field so you can set the scriptableobject instance to them.

Its straightforward and you never have to worry about instantiation. not a single line needs to be written to instantiate it now (aside from the [CreateAssetMenu])

Your “Singleton” is now a project asset and can used seamlessly across scenes, prefabs, and yes even in button Onclicks.

of course its not technically a singleton anymore, but seriously singletons, especially in Unity, are often not used as the design pattern truly intended them to be used.

2 Likes

Thanks man. So this works at run-time, even though it’s UI menu related? Any chance Unity may change this functionality in the future?

needed classes have a public field so you can set the scriptableobject instance to them.

This bit worries me as I may end up with object references spanning multiple scenes that will interfere with clean object garbage collection.

You’d still have to deal with this with singletons anyway. For every event you register, you’ll need to unregister them before allowing gameobjects to be destroyed.

However, scriptableobjects do offer a certain flexibility that singletons don’t – you can more easily control their lifetime. If, for example, you were to quit a game to go back to the main menu, you can destroy all scriptable objects (and in doing so, destroy all events as well).

Actually that’s not true if it’s implemented the way it should be. Code in various scenes and parts of the game should never be holding long term handles to a singleton, that’s bad design that just invites trouble. Instead they should just be calling functions on it and falling out of scope in a relatively tiny time. So there would never be any handles to the singleton from code to clean up. The method you mentioned would have several of those handles to these objects from various classes and would have to be manually managed and cleaned up. I’d rather avoid that scenario as it can introduce an absolute nightmare of headaches.

Unity events however would be the same for both scenarios but are not an issue as unity unbinds them for you when scenes fall out of scope.

I’ll keep what you said in mind, thanks again.

you mean the ScriptableObject Classes? very unlikely. a massive number of built-in unity assets and tools derive from ScriptableObjects and its built to be accessible for end-users to extend upon. ScriptableObjects work perfectly fine and are so engrained in to how Unity can function, there would have to be a serious situation for the base code of the ScriptableObject to change. its more likely that they will extend the base functionality rather than change it.

The fact that its UI Menu related doesn’t change much. Scene Objects will have to be set differently (in that the scene object will call the ScriptableObject and set a property equal to itself) just a little inversion of control.

You can have the inspector draw fields for Scene Objects, but you’ll need to manually create an Editor Script to do so since the default Editor will can’t. The inspector has problems processing fields that reference scene objects, even though ScriptableObjects can still store them. To that end, I usually define them as Properties instead of fields, or as fields with the [NonSerialized] attribute. this way they are still accessible via code but won’t break the default inspector.

Unity will persist the Asset for as long as it needs to.

This means that assets necessarily won’t get immediately garbage collected even if the only object referencing it was destroyed. Unity keeps a back store of assets referenced until they need to be unloaded. And in most cases its default decision on when to unload is sufficient. Typically this means it won’t unload it until the game is turned off or under very specific circumstances (i.e. UnloadUnusedAssets() is called).

I do this differently. yes the gameobject should unregister themselves, but my scriptableObjects make the assumption that they haven’t. thus under certain circumstances the class will check if it has any null references and clean them out. I can post an example EventData class I wrote that handles this perfectly.

on the contrary. UnityEvents actually keeps them, its just on the surface it looks like they are cleaned up.

UnityEvents stores its invocations in 3 lists. the 1st list is persistant, holds all the serialized calls (i.e. the events that you can see in the inspector) the 2nd list hold all the events added programmatically (those added via AddListener). while the final list is a merge of the first two lists.when Invoke() runs UnityEvents iterates that final list, skipping any invalid invocations (any null refs).

it is great that you are looking to take a contract-based approach, and its perfectly possible to set that up with scriptableObjects, doing so will also make Unit Testing a ton easier to do, something which Singletons are notorious at fouling up.

I think we may be talking about different things here.

You don’t hold long term handles to a singleton. However, if the singleton has an event handler, and you register an object’s event with it, you need to unregister it when the object dies. Otherwise, the singleton’s event handler will keep firing events at an object that no longer exists.

One way to work around this is to clear out all events in a singleton when you’re transitioning to another level, but you’re better off using scriptable objects in that case.