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.

2.1 Breaking down the Singleton

 

2.1.1 Diagramming the pattern

 
 

2.1.2 Pros and cons

 
 
 

2.2 Updating a MonoBehaviour into a persistent Singleton

 
 
 

2.2.1 Persisting the Singleton between scenes

 
 
 
 

2.2.2 Testing for duplicate managers

 
 

2.3 Creating a generic Singleton

 
 

2.4 Adding thread-safety to the generic Singleton

 
 
 

2.4.1 A primer on threading

 
 

2.4.2 Thread locking during lazy instantiation

 
 

2.5 Creating Singletons as Scriptable Objects

 

2.6 Summary

 
 
sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage
test yourself with a liveTest