in Tutorial, Unity

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.



Write a Comment