RSS Feed

One Cent added to the Unity Singleton Debate

April 27, 2018

Static variables are not evil, just inflexible. Singleton MonoBehaviour instances are not corrupt either. However, both encourage tight coupling between interested parties.

 

And now for a bit of mild blasphemy. Assets created from scriptable objects, and hence custom assets are Unity supported *singletons*. Create `[SerializeField]` fields and drag an asset of the correct type onto them in the editor. All will reference the same in-memory instance.

 

Using custom assets over traditional singletons provide some benefits:

  • The code is less coupled - or is that more decoupled?

  • Custom assets lend themselves to testing in isolation.

  • Alternative custom assets can be injected into objects that are expecting them. An inventory may depend on location or whether the player is in training mode.

  • It is less error prone to pass custom assets between scenes and projects.

  • Functionality can be more generalised for direct reuse from within the editor without writing as much scaffolding code. A `Float` custom asset, for example, can have listeners that hook into display objects. It can also be updated by sliders and scroll-bars without additional code by adding it to the *On Value Changed* field.

Read about Askowl CustomAssets here. They will eventually be in the Unity Store, but until then, contact me if you want a copy.

 

 

Share on Facebook
Share on Twitter
Please reload

Featured Posts

My limited tests show that Dictionary is faster than `SortedList`. The latter uses `Array.BinarySearch` to find entries. I have read other performance...

How are C# Dictionaries so Fast?

August 27, 2018

1/5
Please reload

Recent Posts

April 12, 2018

Please reload

Archive
Please reload

Search By Tags
Please reload

Follow Us
  • Facebook Basic Square
  • Twitter Basic Square
  • Google+ Basic Square