Reader small image

You're reading from  Game Development Patterns with Unity 2021 - Second Edition

Product typeBook
Published inJul 2021
Reading LevelBeginner
PublisherPackt
ISBN-139781800200814
Edition2nd Edition
Languages
Tools
Right arrow
Author (1)
David Baron
David Baron
author image
David Baron

David Baron is a game developer with over 15 years of experience in the industry. He has worked for some well-known AAA, mobile, and indie game studios in Montreal, Canada. His skill set includes programming, design, and 3D art. As a programmer, he has worked on various games for various platforms, including virtual reality, mobile, and consoles.
Read more about David Baron

Right arrow
Implementing a Game Manager with the Singleton

In this first hands-on chapter, we will review one of the most infamous software design patterns in the field of programming, the Singleton. It could be argued by many that the Singleton is the most widely used pattern among Unity developers, maybe because it's the most straightforward pattern to learn. But it can also quickly become the "duct tape" in our programming toolbox that we reach for every time we need a quick fix for a complex architectural problem.

For instance, when using this pattern, we can quickly establish a simple code architecture revolving around wrapping and managing all the core systems of our game in individual manager classes. Then we could have these managers expose clean and straightforward interfaces that will conceal the inner complexity of the systems. Also, to make sure that these managers...

Technical requirements

This is a hands-on chapter; you will need to have a basic understanding of Unity and C#.

We will be using the following specific Unity engine and C# language concept: Generics.

If unfamiliar with this concept, please review Chapter 3, A Short Primer to Programming in Unity.

The code files of this chapter can be found on GitHub at https://github.com/PacktPublishing/Game-Development-Patterns-with-Unity-2021-Second-Edition/tree/main/Assets/Chapters/Chapter04.

Check out the following video to see the Code in Action: 
https://bit.ly/3wDbM6W

Generics is a compelling C# feature that permits us to defer the type for a class at runtime. When we say a class is generic, it means that it doesn't have a defined object type. This approach is advantageous because we can assign it a specific type when we initialize it. 

Understanding the Singleton pattern

As its name implies, the Singleton pattern's primary goal is to guarantee singularity. This approach means if a class implements this pattern correctly, once initialized, it will have only one instance of itself in memory during runtime. This mechanism can be helpful when you have a class that manages a system that needs to be globally accessible from a singular and consistent entry point.

The design of the Singleton is quite simple. When you implement a Singleton class, it becomes responsible for making sure there's only a single occurrence of itself in memory. Once a Singleton detects an instance of an object of the same type as itself, it will destroy it immediately. Therefore, it's pretty ruthless and doesn't tolerate any competition. The following diagram illustrates the process to a certain degree:

Figure 4.1 – UML diagram of the Singleton pattern

The most important takeaway from this description of the Singleton...

Benefits and drawbacks

These are some of the benefits of the Singleton pattern:

  • Globally accessible: We can use the Singleton pattern to create a global access point to resources or services.
  • Control concurrency: The pattern can be used to limit concurrent access to shared resources.

These are some of the drawbacks of the Singleton pattern:

  • Unit testing: If overly used, the Singleton can make unit testing very difficult. We might end up with Singleton objects being dependent on other Singletons. If one is missing at any moment, the chain of dependency gets broken. This issue often happens when combining Facade and Singleton to set up front-facing interfaces to core systems. We end up with an array of manager classes, each managing a specific core component of the game, all dependent on each other to function. Therefore, it becomes impossible to test and debug in isolation.
  • Laziness: Because of its ease of use, the Singleton is a pattern that can quickly instill faulty programming...

Designing a Game Manager

A standard class we often see in Unity projects is the Game Manager. It's usually implemented as a Singleton by developers, but its responsibility varies from one code base to another. Some programmers use it to manage top-level game states or as a globally accessible front-facing interface to core game systems.

In the context of this chapter, we will give it the singular responsibility of managing a game session. Similar to the concept of a game master in board gaming, it will be responsible for setting up the game for the player. It can also take on additional responsibilities, such as communicating with backend services, initializing global settings, logging, and saving the player's progress.

The critical thing to keep in mind is that Game Manager will be alive for the entire lifespan of the game. Therefore, there will be a singular but persistent instance of it in memory at all times.

The following diagram illustrates the overall concept:

Figure...

Implementing the Game Manager

In this section, we will implement a Singleton and Game Manager class. We will attempt to utilize some core Unity API features to adapt the pattern for use in the engine:

  1. For the first step of the process, we will implement the Singleton class. To make it easier to understand its intricacies, we will split it up into two distinct segments:
using UnityEngine;

namespace Chapter.Singleton
{
public class Singleton<T> :
MonoBehaviour where T : Component {

private static T _instance;

public static T Instance
{
get
{
if (_instance == null)
{
_instance = FindObjectOfType<T>();

if (_instance == null)
{
GameObject obj = new GameObject();
obj.name = typeof(T).Name;
_instance = obj.AddComponent<T>();
}
}

...

Testing the Game Manager

If you wish to test the classes you just wrote in your instance of Unity, then you should go through the following steps:

  1. Create a new empty Unity scene called Init.
  2. In the Init scene, add an empty GameObject and attach the GameManager class to it.
  3. Create several empty Unity scenes, as many as you wish.
  4. In Build Settings under the File menu, add the Init scene at index 0:

Figure 4.3 – Build Settings
  1. Then add your new empty Unity scenes to the Build Settings list, as many as you wish.

If you now start the Init scene, you should see a GUI button named Next Scene as in the following screenshot:

Figure 4.4  Screenshot of the code example in action

If you click on the Next Scene button, you will cycle through each of the scenes you added in Build Settings, and the GUI will persist onscreen. If you stop running the game, you should see in the console log the duration of your session. If you try to add additional GameManagers...

Summary

In this chapter, we tackled one of the most controversial design patterns out there. But we found a way to implement it with a consistent and reusable approach. The Singleton is a pattern that's perfectly suited to Unity's coding model but overusing it can lead you to become too dependent on it. 

In the next chapter, we will review the State pattern, which we will use to implement a controller class for the main ingredient of our game, the racing bike.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Game Development Patterns with Unity 2021 - Second Edition
Published in: Jul 2021Publisher: PacktISBN-13: 9781800200814
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
David Baron

David Baron is a game developer with over 15 years of experience in the industry. He has worked for some well-known AAA, mobile, and indie game studios in Montreal, Canada. His skill set includes programming, design, and 3D art. As a programmer, he has worked on various games for various platforms, including virtual reality, mobile, and consoles.
Read more about David Baron