2 Managing your game with a Singleton
This chapter covers
- Defining, diagraming, and analyzing the pros and cons of the Singleton
- Updating a
MonoBehaviour
script into a persistent Singleton class - Creating a more flexible generic Singleton class using lazy instantiation
- Making the generic Singleton class thread-safe for multithreaded environments
- Creating Singleton instances as Scriptable Object assets in your project
In the last chapter, we talked about the basics of software architecture, common problems that design patterns solve, and how they fit into Unity projects. We also discussed the scope and focus of this book, and what you as a reader should know before diving in. In this chapter, we’ll start our practical journey by exploring the Singleton design pattern, which helps in situations where you want a global access point to a single instance of a class. In Unity and game programming, this scenario is common with manager or service classes that need to keep track of global state information and system-wide utilities.