Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
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
€17.99 €26.99
Paperback
€22.99 €33.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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
Estimated delivery fee Deliver to Cyprus

Premium delivery 7 - 10 business days

€32.95
(Includes tracking information)

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 : 9781805120285
Languages :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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
Estimated delivery fee Deliver to Cyprus

Premium delivery 7 - 10 business days

€32.95
(Includes tracking information)

Product Details

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

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.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
€189.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
€264.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 73.97 107.97 34.00 saved
Learning Design Patterns with Unity
€22.99 €33.99
Mastering UI Development with Unity
€25.99 €37.99
Hands-On Unity  Game Development
€24.99 €35.99
Total 73.97 107.97 34.00 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

Most Recent
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
Most Recent

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
Danial Jumagaliyev Oct 25, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
It's full of great tips in organizing your code in Unity and I recommend checking it out if you are into learning game development with the Unity engine.
Amazon Verified review Amazon
Florida MTB’r Oct 14, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book breaks down many important game development techniques. Many of which I have heard before but never worked with. This does a good job of introducing a design pattern, then dives deeper into making it its most efficient / clean implementation.The book offers sample projects to download. I never used those but was able to follow along with the sample Unity code and setup regardless.I now have integrated many of these techniques into my usual game dev process. Great book for learning at an intermediate level.
Amazon Verified review Amazon
Tyree Weston Sep 16, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
A good read to build on existing knowledge. As the title suggests, this book is a way to explain common design patterns and shed some light on different situation that can be made more efficient to apply said patterns. That saidTHIS IS NOT A BOOK FOR BEGINNERSThis is not intro to Unity, intro to C#, or an intro to programming in general. The intended audience who will gain information from this book need to be generally familiar with unity. With that in mind, Harrison Ferrone did a great job explaining the concept presented and provided excellent examples.
Amazon Verified review Amazon
Paul Southworth Sep 10, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book seems to cover quite a range of design patterns and even includes things on how it's been used within a game setting using the Unity engine.although this book is not meant for beginners it's a book that you can keep within your shelf, especially If you end up looking at the overview of the different chapters. you can see an explanation of how that specific pattern is being used
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela