Singleton Design Pattern

Miguel Pacheco
3 min readDec 13, 2023

--

A singleton class is a class that can be accessed globally by any other class. We create an instance of a class and then use that instance to access the class members without having to create a reference to the class.

Let’s start by creating a new empty game object and call it Spawn Manager.

  • Create a new script
  • Attach it to the Spawn Manager

Open the C# script and create a private static variable of type (Class Name).

Now we are going to create a property that will return the instance of the class.

The last thing we need to do in order for the singleton to work is to initialize the instance. In void Awake make sure to initialize the instance variable.

Now we can create a public function and access it from another script.

I’m going to create a public function inside the Spawn Manager class that is going to spawn a sphere in a random location.

If we take a look at the inspector, we need a sphere prefab reference.

Create a sphere and drop it onto the assets folder to make it a prefab. We can delete the one in the hierarchy.

Drop the sphere prefab onto the Spawn Manager field.

I want the sphere to spawn every time I press the space key. I’ll create an Input Manager class that will communicate with the Spawn Manager Singleton class to spawn the sphere.

Now we can play the game and we should see spheres spawning on the screen in random locations.

--

--