in Tutorial, Unity

Unity – Reusable Singleton Tutorial

Singletons are very useful in Unity. They can be used to store variable values and keep it after changing Scenes, e.g.

I like to use a MyApplication class as Singleton in my games, managing all variables, objects and configurations that need to persist throughout the game.

Searching for Unity Singleton Patterns on Google, most of the time you will find:

  • Simple and small codes, but with some issues;
  • Long codes that make your classes “dirty”.

But then I found a cool pattern in this wiki http://wiki.unity3d.com/index.php/Singleton.

I took this pattern, made some changes and now I share here what I called as Reusable Singleton.

It’s a Singleton design pattern that can be reused extending it on subclasses. Using this script, You will not need to write the singleton initializers in your classes. Just make your class extends Singleton and it will automatically have the singleton features! Just 1 line of code!

This is a MonoBehaviour script, so you can use the Coroutines.

Creating Singleton Base Class

First, you need to create the “Singleton.cs” script. All your own singleton classes will extend it. (You can also download this script here)

Creating Your Class

Create your class that you want to be a singleton, and make it extends Singleton.

Usage Example

Now you can call your singleton class by Instance:

 


Now you can create multiple singleton classes, just extending Singleton.cs.
Say goodbye to rewriting Singleton methods over and over again.

You can download the source codes here.

 

Write a Comment

Comment