Unity – Creating Singleton From Prefab Tutorial

In the previous tutorial Reusable Singleton Tutorial I showed how to create a singleton class that can be reused extending it on subclasses, so you don’t need to write the singleton initializers in your classes.

Now you’ll learn how to use this singleton from a prefab. It is very useful that you can add scripts and set the properties values on your prefab using Unity Editor and have them loaded with your singleton.

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). It’s almost the same script created in the previous tutorial, but this time we’ll check for existing prefab on resources folder to instantiate it.

Creating Your Class

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

Creating the Prefab

Create a game object and add your Singleton Class to it.

MySingletonExample Prefab

Convert your game object to prefab and put it on Resources Folder.
IMPORTANT: The prefab needs to have the same name as your Singleton Class (MySingletonExample in this example)

Resources Folder

Remove the Game Object from Scene (It will be created when you call MySingletonExample.Instance).

Usage Example

Now you can call your singleton class by Instance:

When you call your singleton it will check for existing prefab with the same name on Resources folder to instantiate it. If none prefab is found, the singleton will be created as new.


Now you can set values on your Singleton Prefab Object and have them loaded when your Singleton is instantiated.

You can download the source codes here.

 

 

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! Continue reading