Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Learning Design Patterns with Unity
Learning Design Patterns with Unity

Learning Design Patterns with Unity: Learn the secret of popular design patterns while building fun, efficient games in Unity 2023 and C#

eBook
$24.99 $35.99
Paperback
$30.99 $44.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Table of content icon View table of contents Preview book icon Preview Book

Learning Design Patterns with Unity

Managing Access with the Singleton Pattern

In the last chapter, we went over the core of what design patterns are, the common problems they solve, and how we’ll go about learning and implementing each of them throughout our adventure. In this chapter, we’ll start our practical journey by exploring the Singleton pattern, which helps when you want a single instance of a class to be globally accessible. For applications and games, you’ll commonly see this type of functionality with manager or service classes that keep track of global state or provide access to system-wide utilities. However, we need to be aware of potential risks with global state (and how to protect our newly accessible data), which we’ll discuss later in the chapter.

Anytime you bring up the Singleton pattern in programming circles, you’re likely to hear an audible sigh, some hushed booing, and maybe even an angry shout or two. And that’s precisely why I like to teach this...

Technical requirements

To get started:

  1. Download or clone the GitHub repository at https://github.com/PacktPublishing/C-Design-Patterns-with-Unity-First-Edition.
  2. Open the Ch_02_Starter project folder in Unity Hub.
  3. Navigate to Assets | Scenes, and double-click on SplashScreen.

The starter project for this chapter has two scenes – a splash screen with the title of our little game and a button to start the adventure. When you click Start, the game transitions to a new scene, where you can move a capsule around a small arena and collect spheres.

As for the scripts:

  • Item.cs is attached to each Item prefab that is responsible for destroying itself when there’s a collision.
  • Manager.cs stores our score and loads the next scene.
  • Player.cs is responsible for moving our character around the scene using the WASD or arrow keys.
  • ScoreUI.cs stores a Text object so that we can set an initial score value on our scene canvas...

Breaking down the pattern

First, it’s important to recognize scenarios where the Singleton pattern is useful and doesn’t just add unnecessary complexity to your code. The original Gang of Four text says you should consider using the Singleton pattern when:

You need to limit a class to a single instance and have that unique instance be accessible to clients through a global access point.

For example, your computer should only have one filesystem, in the same way that your body should only have one heart (for best performance). A global variable can take care of the accessibility, and in the case of C#, a static variable fits the bill nicely. When you put it all together, a singleton class is responsible for initializing, storing, and returning its own unique instance, as well as protecting against duplicate instance requests.

Figure 2.1 describes a game scenario where a manager script stores game state data and maybe some shared functionality.

In this...

Updating a MonoBehavior into a persistent singleton

Imagine you are building a platforming game where the player collects items through multiple levels. Your team lead asks you to create a manager script to track the player’s score, handle scene transitions, and ensure there’s always one unique instance in a scene. Our first task is to ensure that the game manager class in the starter project only ever has one active instance.

Open Manager.cs and update the code to match the following code, which sets the singleton instance or destroys the GameObject that the script is attached to if an instance already exists:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class Manager : MonoBehaviour
{
    // 1
    public static Manager Instance;    
    public int score = 0;
    public int startingLevel = 1;
    // 2
    void Awake()    
    {
        // 3
        if(Instance...

Creating a generic singleton

Imagine you want to make the singleton more flexible, reusable, and maintainable. The previous implementation works, but it’s hardcoded into Manager.cs, which won’t help us if we want different classes to act like singletons. A better solution is to write a generic singleton that other classes can easily subclass.

We’re using a generic approach instead of subclassing the singleton class because we want the same design pattern implementations applied to different types. If we wanted the same functionality implemented in different ways across different singletons, subclass and traditional Object-oriented inheritance would be the way to go.

Figure 2.13 describes a generic singleton script that other manager classes can inherit from. Each subclassed manager has the same underlying Singleton structure, but each one can also add its own unique functionality and variables.

Diagram  Description automatically generated

Figure 2.13: Multiple manager classes...

Adding thread safety to the generic singleton

In this section, we’re going to focus on making our generic singleton thread-safe by guarding against different threads potentially creating more than one instance of the singleton. For example, imagine you need to process an algorithm that finds all enemies within a set distance, as well as their positions and orientations. Doing this on the main thread might decrease your frame rate and slow down other processes in your game. However, if you separate the algorithm into a separate thread, Unity’s main thread is free to keep running the essential parts of the game while the sub-thread does its work.

Thread safety in multithreaded environments is a huge topic and has additional implications when using Unity APIs. For a deeper dive, check out .NET Multithreading by Alan Dennis at https://www.manning.com/books/net-multithreading.

If you’re new to the concept of threading, it helps to think of your...

Creating singletons as ScriptableObjects

Imagine you and your design team need to create, configure, and test singleton classes in the Unity Editor. Using ScriptableObjects as data containers not only frees you from attaching your scripts to GameObjects but also gives you the freedom to create singleton assets from the Asset menu. Both added features make scriptable objects a good fit to address testing concerns with the Singleton pattern, and it is much easier for non-programming members of your team to work with them.

Your last task in this chapter is to create a generic singleton as a ScriptableObject asset in the project. In the Scripts folder, create a new C# script, name it ScriptableSingleton, and update its code to match the following code. This script creates a generic ScriptableObject class that we can use to fetch a unique instance from the project resources when queried:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// 1
public...

Summary

If this was your first foray into design patterns, congrats and welcome to the club! We’ve covered quite a bit in this chapter, from a super-vanilla singleton hardcoded into a single class all the way to lazy instantiation, generics, and thread safety – not to mention using ScriptableObject assets as containers for design pattern code.

Keep in mind that your singleton classes are most useful when you only want a single class instance, a global point of access, and persistence throughout the Unity game lifecycle. You have the choice of lazily instantiating your singleton objects, which helps with accessing information your project may only have after compiling (not to mention the singleton itself won’t be created until it’s needed). You can also go for a generic solution, which can be a subclass or even a ScriptableObject!

However, it’s important to remember that any globally accessible objects can have adverse effects if you’...

Further reading

  • Generics open up a whole new world of programming possibilities (which is why I included a generic solution in this chapter), but I’d recommend reading up on the topic at https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/types/generics.
  • ScriptableObjects are the perfect way to create data containers in your Unity projects (and we’ll use them in almost every chapter going forward), but I’d also recommend checking out the documentation at https://docs.unity3d.com/Manual/class-ScriptableObject.html.
  • Multithreading is a bit of an advanced topic outside the scope of this book, but being able to perform multiple operations at the same time is a useful tool in your toolbox. If you want to know more about this topic, head over to the documentation at https://learn.

Leave a review!

Enjoying this book? Help readers like you by leaving an Amazon review. Scan the QR code below to get a free eBook of your choice.

...
Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Craft engaging Unity 2023 games while mastering design patterns like Singleton, Object Pool, and more
  • Write clean, reusable C# code using creational, behavioral, and structural patterns, tailored for the game development environment
  • Go beyond basic design pattern usage and learn to customize and extend them for your unique game design needs

Description

Struggling to write maintainable and clean code for your Unity games? Look no further! Learning Design Patterns with Unity empowers you to harness the fullest potential of popular design patterns while building exciting Unity projects. Through hands-on game development, you'll master creational patterns like Prototype to efficiently spawn enemies and delve into behavioral patterns like Observer to create reactive game mechanics. As you progress, you'll also identify the negative impacts of bad architectural decisions and understand how to overcome them with simple but effective practices. By the end of this Unity 2023 book, the way you develop Unity games will change. You'll emerge not just as a more skilled Unity developer, but as a well-rounded software engineer equipped with industry-leading design patterns.

Who is this book for?

This book is your perfect companion if you're a Unity game developer looking to level up your C# skills and embrace industry standards for building robust games. Knowledge of Unity and basic C# programming is recommended.

What you will learn

  • Implement a persistent game manager using the Singleton pattern
  • Spawn projectiles efficiently with Object Pooling for optimized performance
  • Build a flexible crafting system using the Factory Method pattern
  • Design an undo/redo system for player movement with the Command pattern
  • Implement a state machine to control a two-person battle system
  • Modify existing character objects with special abilities using the Decorator pattern

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : May 31, 2024
Length: 676 pages
Edition : 1st
Language : English
ISBN-13 : 9781805124160
Languages :
Concepts :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want

Product Details

Publication date : May 31, 2024
Length: 676 pages
Edition : 1st
Language : English
ISBN-13 : 9781805124160
Languages :
Concepts :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 98.96 142.97 44.01 saved
Learning Design Patterns with Unity
$30.99 $44.99
Mastering UI Development with Unity
$34.98 $49.99
Hands-On Unity  Game Development
$32.99 $47.99
Total $ 98.96 142.97 44.01 saved Stars icon

Table of Contents

22 Chapters
Priming the System Chevron down icon Chevron up icon
Managing Access with the Singleton Pattern Chevron down icon Chevron up icon
Spawning Enemies with the Prototype Pattern Chevron down icon Chevron up icon
Creating Items with the Factory Method Pattern Chevron down icon Chevron up icon
Building a Crafting System with the Abstract Factory Pattern Chevron down icon Chevron up icon
Assembling Support Characters with the Builder Pattern Chevron down icon Chevron up icon
Managing Performance and Memory with Object Pooling Chevron down icon Chevron up icon
Binding Actions with the Command Pattern Chevron down icon Chevron up icon
Decoupling Systems with the Observer Pattern Chevron down icon Chevron up icon
Controlling Behavior with the State Pattern Chevron down icon Chevron up icon
Adding Features with the Visitor Pattern Chevron down icon Chevron up icon
Swapping Algorithms with the Strategy Pattern Chevron down icon Chevron up icon
Making Monsters with the Type Object Pattern Chevron down icon Chevron up icon
Taking Data Snapshots with the Memento Pattern Chevron down icon Chevron up icon
Dynamic Upgrades with the Decorator Pattern Chevron down icon Chevron up icon
Converting Incompatible Classes with the Adapter Pattern Chevron down icon Chevron up icon
Simplifying Subsystems with the Façade Pattern Chevron down icon Chevron up icon
Generating Terrains with the Flyweight Pattern Chevron down icon Chevron up icon
Global Access with the Service Locator Pattern Chevron down icon Chevron up icon
The Road Ahead Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.8
(30 Ratings)
5 star 86.7%
4 star 10%
3 star 3.3%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Emmanuel Mensah Oct 29, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Harrison Ferrone’s book is a fantastic introduction to design patterns for Unity developers. Right from the basics, like the difference between software architecture and software design, to advanced patterns such as Visitor and Decorator, Ferrone guides you with clarity and enthusiasm. The examples are relevant and explained in a way that builds a solid understanding without overwhelming the reader. I especially appreciated how he addresses common pitfalls with each pattern, which is often overlooked in technical books. It’s a well-organised guide for game developers wanting to produce clean, maintainable, and scalable code in Unity.
Amazon Verified review Amazon
Eric Montoya Jun 26, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I received this as an ebook. This book is great for learning C# design patterns to have clean code and optimize your code. I really like how Harrison gives examples how to use each design patterns and pushes the envelope on what you could do with the patterns.He also presents the pros and cons of each pattern. Advising how to use each pattern. Then he teaches you how to program each pattern.This is a must book to take your Unity, C# programming, and game developer skills to the next level!!!
Amazon Verified review Amazon
Nitin Dhami Jun 24, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Whether you are an experienced developer or starting out in your journeyThis book is not going to disappoint you at all I came across this book on linkedinand that was a good recommendation it helps you understand Design patterns w.r.t games how to createmaintainable code bases and be a pro in it.This discuss all the aspects of how to be a senior engineer.Highly recommended.
Amazon Verified review Amazon
Theodor Florian Purcaru Jun 18, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
“Learning Design Patterns with Unity” is a great book that offers a comprehensive guide to understanding and implementing design patterns in Unity. It is a great asset for beginners as an introduction to the most common problems and the best solutions you’d encounter as a Unity developer. It’s also a useful tool for advanced users wanting a refresher on patterns they might not encounter on a daily basis.The author, Harrison Ferrone, has done an excellent job presenting these solutions with near real world scenarios that can be quickly retrofitted in your own game. I can actually say many of my common solutions for game jams or even at work, are similar to what we see here, showing that the code can indeed work in the real world, which is also very useful and encouraging for applying what you learn directly on your own projects. Ferrone’s writing style is engaging and easy to follow, making it suitable for both beginners and experienced developers.This book will undoubtedly enhance your coding skills and inspire you to write better, more efficient code. Happy reading! 📚
Amazon Verified review Amazon
Wolfgang Hendrix Aug 24, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book masterfully explores crafting reusable code through design patterns in Unity and C#. It tackles creational, behavioral, and structural patterns, offering strategies for when and how to apply them best. With clear guidance and practical examples, it’s a vital resource for developers at any stage, ensuring your code is efficient and maintainable. For those devoted to game development or software design, this book is a must.
Amazon Verified review Amazon