Game Development Patterns with Unreal Engine 5: Build maintainable and scalable systems with C++ and Blueprint
()
About this ebook
Design patterns serve as a toolkit of techniques and practices that enable you to write code that’s not only faster, but also more manageable. With this book, you’ll explore a range of design patterns and learn how to apply them to projects developed in Unreal Engine 5.
You’ll begin by delving into the foundational principles of coding and develop a solid understanding of the concepts, challenges, and benefits of using patterns in your code. As you progress, you’ll identify patterns that are woven into the core of Unreal Engine 5 such as Double Buffer, Flyweight, and Spatial Partitioning, followed by some of the existing tool sets that embody patterns in their design and usage including Component, Behavior Tree, and Update.
In the next section of the book, you’ll start developing a series of gameplay use cases in C++ to implement a variety of design patterns such as Interface and Event-based Observers to build a decoupled communications hierarchy. You’ll also work with Singleton, Command, and State, along with Behavioral Patterns, Template, Subclass Sandbox, and Type Object. The final section focuses on using design patterns for optimization, covering Dirty Flag, Data Locality, and Object Pooling.
By the end, you’ll be proficient in designing systems with the perfect C++/Blueprint blend for maintainable and scalable systems.
Stuart Butler
Stuart Butler, who has lived for most of his life at the western end of the French Pyrenees, is a journalist, guidebook author and award-winning photographer. His areas of speciality are the Pyrenees, Himalya and East Africa. He has written over a hundred guidebooks for Lonely Planet, Rough Guide and Bradt, as well as a number of specialist hiking and wildlife watching guides on the Himalaya, France and Spain. He writes frequently about conservation, the environment and hiking for the BBC, Geographical magazine, New York Times, Sierra magazine and the i newspaper. He's also the tourism manager of the Nashulai Maasai Conservancy ( nashulai.com ), a community wildlife reserve in Kenya. He also works with the Himalayan trekking and tour company, Third Rock Adventures ( thirdrockadventures.com ) and manages Nashulai Journeys ( nashulaijourneys.com ), a specialist eco-tourism company with a focus on hiking holidays. Stuart is married with two children, who also enjoy hiking in the Pyrenees. His website is stuartbutlerjournalist.com and walkingwiththemaasai.com .
Read more from Stuart Butler
Lonely Planet Russia Rating: 4 out of 5 stars4/5Lonely Planet Trans-Siberian Railway Rating: 4 out of 5 stars4/5Lonely Planet China Rating: 5 out of 5 stars5/5Lonely Planet Nepal Rating: 4 out of 5 stars4/5Lonely Planet West Africa Rating: 3 out of 5 stars3/5Lonely Planet Spain & Portugal's Best Trips Rating: 5 out of 5 stars5/5Travel Guide Brazil Rating: 0 out of 5 stars0 ratingsLonely Planet Best of Central America Rating: 0 out of 5 stars0 ratingsTrekking the GR10: Through the French Pyrenees: Le Sentier des Pyrenees Rating: 0 out of 5 stars0 ratingsLonely Planet Best Day Hikes Spain Rating: 0 out of 5 stars0 ratingsLonely Planet Best Day Walks Spain Rating: 0 out of 5 stars0 ratings
Related to Game Development Patterns with Unreal Engine 5
Related ebooks
Unreal Engine From Zero to Proficiency (Beginner): Unreal Engine from Zero to Proficiency, #2 Rating: 0 out of 5 stars0 ratingsBeginning C++ Game Programming: Learn C++ from scratch by building fun games Rating: 0 out of 5 stars0 ratingsMoving from Unity to Godot: An In-Depth Handbook to Godot for Unity Users Rating: 0 out of 5 stars0 ratingsUnity 5 for Android Essentials Rating: 4 out of 5 stars4/5Construct 2 Game Development by Example Rating: 0 out of 5 stars0 ratingsUnity 3D Game Development: Designed for passionate game developers—Engineered to build professional games Rating: 0 out of 5 stars0 ratingsGetting Started with Unity 5 Rating: 5 out of 5 stars5/5Beginning Game AI with Unity: Programming Artificial Intelligence with C# Rating: 0 out of 5 stars0 ratingsMastering Unreal Engine 4.X Rating: 0 out of 5 stars0 ratingsUnity Artificial Intelligence Programming: Add powerful, believable, and fun AI entities in your game with the power of Unity Rating: 0 out of 5 stars0 ratingsBlueprints Visual Scripting for Unreal Engine Rating: 0 out of 5 stars0 ratingsUnity AI Programming Essentials Rating: 0 out of 5 stars0 ratingsCreating ELearning Games with Unity Rating: 0 out of 5 stars0 ratingsVideo Game Careers - Beginners Guide: Video Game Careers, #1 Rating: 0 out of 5 stars0 ratingsBuilding an FPS Game with Unity Rating: 0 out of 5 stars0 ratingsBuilding JavaScript Games: for Phones, Tablets, and Desktop Rating: 0 out of 5 stars0 ratingsProcedural Content Generation for Unity Game Development Rating: 0 out of 5 stars0 ratingsUnity Animation Essentials Rating: 0 out of 5 stars0 ratingsUnity Game Development Blueprints Rating: 0 out of 5 stars0 ratingsAndroid Game Programming by Example Rating: 0 out of 5 stars0 ratingsUnity 5.x By Example Rating: 0 out of 5 stars0 ratingsLearning C++ by Creating Games with UE4 Rating: 3 out of 5 stars3/5Learn Python by Coding Video Games (Intermediate): Learn Python by Coding Video Games, #2 Rating: 0 out of 5 stars0 ratingsBuilding an RPG with Unreal Rating: 0 out of 5 stars0 ratingsMastering Unity Scripting Rating: 0 out of 5 stars0 ratings
Programming For You
Excel : The Ultimate Comprehensive Step-By-Step Guide to the Basics of Excel Programming: 1 Rating: 5 out of 5 stars5/5Excel 101: A Beginner's & Intermediate's Guide for Mastering the Quintessence of Microsoft Excel (2010-2019 & 365) in no time! Rating: 0 out of 5 stars0 ratingsSQL QuickStart Guide: The Simplified Beginner's Guide to Managing, Analyzing, and Manipulating Data With SQL Rating: 4 out of 5 stars4/5Coding All-in-One For Dummies Rating: 4 out of 5 stars4/5Grokking Algorithms: An illustrated guide for programmers and other curious people Rating: 4 out of 5 stars4/5Python QuickStart Guide: The Simplified Beginner's Guide to Python Programming Using Hands-On Projects and Real-World Applications Rating: 0 out of 5 stars0 ratingsPython Programming : How to Code Python Fast In Just 24 Hours With 7 Simple Steps Rating: 4 out of 5 stars4/5HTML & CSS: Learn the Fundaments in 7 Days Rating: 4 out of 5 stars4/5Python Machine Learning By Example Rating: 4 out of 5 stars4/5Python: For Beginners A Crash Course Guide To Learn Python in 1 Week Rating: 4 out of 5 stars4/5Learn to Code. Get a Job. The Ultimate Guide to Learning and Getting Hired as a Developer. Rating: 5 out of 5 stars5/5SQL: For Beginners: Your Guide To Easily Learn SQL Programming in 7 Days Rating: 5 out of 5 stars5/5Learn PowerShell in a Month of Lunches, Fourth Edition: Covers Windows, Linux, and macOS Rating: 5 out of 5 stars5/5PYTHON: Practical Python Programming For Beginners & Experts With Hands-on Project Rating: 5 out of 5 stars5/5JavaScript All-in-One For Dummies Rating: 5 out of 5 stars5/5Unreal Engine from Zero to Proficiency (Foundations): Unreal Engine from Zero to Proficiency, #1 Rating: 3 out of 5 stars3/5Python: Learn Python in 24 Hours Rating: 4 out of 5 stars4/5Linux: Learn in 24 Hours Rating: 5 out of 5 stars5/5C# Programming from Zero to Proficiency (Beginner): C# from Zero to Proficiency, #2 Rating: 0 out of 5 stars0 ratingsSpies, Lies, and Algorithms: The History and Future of American Intelligence Rating: 4 out of 5 stars4/5
Reviews for Game Development Patterns with Unreal Engine 5
0 ratings0 reviews
Book preview
Game Development Patterns with Unreal Engine 5 - Stuart Butler
Game Development Patterns with Unreal Engine 5
Copyright © 2023 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Group Product Manager: Rohit Rajkumar
Publishing Product Manager: Vaideeshwari Muralikrishnan
Book Project Manager: Sonam Pandey
Content Development Editor: Debolina Acharyya
Technical Editor: Simran Ali
Copy Editor: Safis Editing
Proofreader: Safis Editing
Indexer: Tejal Daruwale Soni
Production Designer: Gokul Raj S.T
DevRel Marketing Coordinators: Nivedita Pandey, Namita Velgekar, and Anamika Singh
First published: December 2023
Production reference: 1071223
Published by
Packt Publishing Ltd.
Grosvenor House
11 St Paul’s Square
Birmingham
B3 1RB, UK
ISBN 978-1-80324-325-2
www.packtpub.com
To my wife, Becky, for her unrivaled love, support, and understanding as I pursue my career goals, and for always being by my side throughout all of the challenges. To my boys, Jack, Zach, and Lincoln, for their support and excitement at the prospect of me writing an actual book.
– Stuart Butler
To my wife, Rosie – her unconditional love and support for my efforts to reach my goals continue to keep me sane and true. To my parents, Martin and Sheila, for giving me the foundation I needed to succeed. To my sister, Amy, and her husband, Phil, for inspiring me to drive for better.
– Tom Oliver
Foreword
Stuart Butler and Tom Oliver are two of the most talented game developers and educators that I have had the pleasure of working with. Both are experts in the technologies that underpin modern video games and have a wealth of experience in turning imagination into reality through the creative sorcery of design and code.
Like most coders, my first programming project was getting the terminal to print out Hello World.
From here, I started to tinker, making increasingly more complex and challenging projects in a very solution-focused manner. My code was often a sprawling mess of comments and redundancy; it wasn’t very efficient, but it worked (usually). It wasn’t until I had to revisit (and decipher) old code or if I had to collaborate with fellow developers that my cluttered code became a problem. Fortunately, my teacher introduced me to the world of design patterns.
Design patterns are one of the most valuable assets in the game developer’s arsenal. They keep your workflow manageable and efficient, and common patterns make collaboration easier. In the fast-paced, multi-disciplinary world of game development, design patterns are an essential ally.
Through this book, you will learn the essential principles of programming and build a strong understanding of the value and application of design patterns. You will benefit from an appreciation of how these approaches work in practice through working with one of the most powerful tools in game development, the Unreal Engine 5 games engine. You will learn the essential grounding to allow you to seamlessly blend between the Unreal Blueprint visual scripting system and C++, allowing you to develop complex and scalable video game projects.
Butler and Oliver are exceptional developers, designers, and world-leading experts in the Unreal Engine. The knowledge they share through this book will be invaluable to anyone working with this tool. Their step-by-step approach and the strong focus on practical examples and learning through doing will help you get the most out of your game’s development projects.
Unlock the full potential of the Unreal Engine with Games Development Patterns.
Prof. Christopher J. Headleand
National Teaching Fellow, Head of Games Development,
Staffordshire University
Contributors
About the authors
Stuart Butler is an Unreal Engine expert with over 13 years of experience in teaching game development in higher education. Stuart has published projects in a multitude of disciplines, including technical design, art, and animation. Stuart is the course director for games technology at Staffordshire University, responsible for the programming team within the UK’s largest games education department. Stuart is also an Unreal Authorized Instructor and has published work as an educational content creator with Epic Games, developing learning materials for Unreal Engine 5. Stuart holds a BSc (hons) in computer games design and a PgC in higher and professional education.
I would like to thank my family for their unwavering support and my colleagues at Staffs Uni for inspiring me to pursue my ambitions. I’d also like to thank Greg Penninck, Bobbie Fletcher, and Justin Mohlman especially, for believing in me throughout my career so far and providing some amazing opportunities. Lastly, I’d like to thank Tom for joining me on this adventure to becoming published authors.
Tom Oliver is a game programmer with over 10 years of experience in working with game engines, both commercially and in an educational capacity. He has used Unreal Engine for contract work both in and out of the games industry, from creating systems for games to mixed reality training simulations. Tom is a senior lecturer and course leader at Staffordshire University, responsible for maintaining the award-winning structure and teaching of the course in the UK’s largest games education department. Tom holds a BSc (hons) in computer games design and programming and a PgC in higher and professional education. Tom specializes in researching gameplay systems driven by mathematical phenomena.
I would like to thank my family for always being my tribe and my colleagues at Staffs Uni for being my squadron. Special thanks to Yvan Cartwright and Paul Roberts for starting the programming fire in me – I hope that this book shows that I paid attention, and Davin Ward, for sticking with me for the last decade. Lastly, thank you to Stu for navigating these word-filled waters with me – we did the thing.
About the reviewer
Ahmed Farrag, a proficient game developer with an MSc in computer science, excels in Unreal Engine development and problem-solving. He is currently the Unreal Engine lead developer at TransformologyXR, building on a rich background that includes contributions to Rumbling Games Studios, Astra Nova, Epoch, and Camouflage Studios.
Ahmed’s portfolio boasts a range of titles, including the successfully published titles Vulcan Runner and Knights of Lights: The Prologue, and the upcoming releases Atlantis Heroes and Kingdom Sports. His unwavering commitment to innovation in delivering exceptional interactive experiences makes him a standout in the industry.
Table of Contents
Preface
Part 1: Learning from Unreal Engine
1
Understanding Unreal Engine 5 and its Layers
Technical requirements
Introducing Unreal Engine 5
Installing Unreal Engine 5 and preparing your development environment
The Fuzzy
layer – bridging the gap from C++ to Blueprint
Property Specifiers
Function Specifiers
Useful inheritance
Translating back from Blueprint to C++
Worked example
Summary
Questions
Answers
2
Hello Patterns
Technical requirements
S.O.L.I.D. principles
Single responsibility
Open-closed
Liskov substitution
Interface segregation
Dependency inversion
Exploring solutions to common problems
The moving box problem
The rotating box problem
The cascading cast chain problem
The trade-off
Summary
3
UE5 Patterns in Action – Double Buffer, Flyweight, and Spatial Partitioning
Technical requirements
Double buffer
Flyweight
Spatial partitioning
Introducing World Partition
Understanding when objects are loaded
Ensuring actors are loaded when required
Enabling World Partition on an existing level
Summary
4
Premade Patterns in UE5 – Component, Update Method, and Behavior Tree
Technical requirements
Understanding and creating components
Applying the update method for prototyping gameplay
Working with behavior trees
Creating the AI controller
Creating the Blackboard asset
Building the behavior tree
Summary
Part 2: Anonymous Modular Design
5
Forgetting Tick
Technical requirements
Before we begin
A world that ticks
A clock that stops
Event driven systems
Summary
6
Clean Communication – Interface and Event Observer Patterns
Technical requirements
Interfacing communication across classes in UE5
Blueprint interfaces
Interface events versus functions
Interfaces in C++
Building an example interface communication
Implementing event delegate communication across UE5
Event delegates in Blueprint
Event delegates in C++
Building a useful delegate tool
Summary
7
A Perfectly Decoupled System
Technical requirements
Using UML to plan a sample hierarchy
What are the types of class relations?
What is a sequence diagram?
Decoupling the reference train
Modularity and decoupling
Establishing infrastructure
Implementing decoupled design in an example
Benefits of decoupling
Summary
Part 3: Building on Top of Unreal
8
Building Design Patterns – Singleton, Command, and State
Technical requirements
Implementing a Singleton pattern – understanding why it’s a Pandora’s box
Implementing the Command pattern for different use cases
Command pattern for undo functionality in Blueprint Utilities
Command pattern for gameplay in C++
Creating the many levels of a state machine
Exploring animation state machines
Enum/switch implementation
Static versus instanced states
Concurrent state machines
Hierarchical state machines
Pushdown automata
Summary
9
Structuring Code with Behavioral Patterns – Template, Subclass Sandbox, and Type Object
Technical requirements
Exploring the template pattern
Building the template (parent class)
Creating child classes
Template pistol
Template shotgun
Understanding subclass sandbox
Building the sandbox (parent class)
Creating child classes
Sandbox pistol
Sandbox shotgun
Type object pattern
Variants
Data Tables
Data Assets
Summary
10
Optimization through Patterns
Technical requirements
Using dirty flags to reduce unnecessary processing
Application of dirty flags
How data locality affects code efficiency
Hot/cold splitting
Contiguous arrays
Object pooling our resources to save time later
Implementing object pooling
Making an object pool
Summary
Index
Other Books You May Enjoy
Preface
Welcome to Game Development Patterns with Unreal Engine 5. In this book, we will be exploring design patterns, a series of tools and practices through which we can learn to write faster and easier to work with code. We will also be exploring a range of different patterns and learn to apply them to project development in Unreal Engine 5.
By the end of this book, you will be able to design systems with the perfect C++/Blueprint blend for maintainable and scalable systems.
Who this book is for
This book is targeted at beginner and intermediate game developers who are working with Unreal Engine and would like to improve their C++ coding practices. This book will help you produce clean, reusable code using design patterns. We will be covering some introductory tasks to show the key fundamentals of using Unreal Engine 5 and some of its tools; however, we will not be teaching you Unreal Engine from scratch.
You would benefit from having some experience with Unreal Engine 4 or 5, but you do not need a deep working understanding of the toolset.
What this book covers
Chapter 1
, Understanding Unreal Engine 5 and Its Layers, explores Unreal Engine 5 and offers a brief history. We will look at the fuzzy
layer that bridges the gap between C++ and Blueprint and learn how to translate Blueprint back to C++.
Chapter 2
, Hello Patterns
, focuses on the principles that underpin all good code. We will explore design patterns as well as some common Blueprint mistakes, looking at how we can fix them.
Chapter 3
, UE5 Patterns in Action – Double Buffer, Flyweight, and Spatial Partitioning, discovers how Unreal Engine 5 employs these three design patterns as we explore a range of tools within the engine.
Chapter 4
, Premade Patterns in UE5 – Component, Behavior Tree, and Update Method, utilizes the pre-built implementations of these three design patterns and explores the tools within the engine to expand simple systems.
Chapter 5
, Forgetting Tick, develops your understanding of Tick, looks at why its usage can cause issues, and explores two approaches to building systems without it.
Chapter 6
, Clean Communication – Interface and Event Observer Patterns, explores design patterns that allow us to improve how different actors communicate with each other, producing more efficient solutions to communication.
Chapter 7
, A Perfectly Decoupled System, discovers how we can use UML as a methodology for planning class hierarchies, to decouple the reference train.
Chapter 8
, Building Design Patterns – Singleton, Command, and State, examines these three design patterns to understand their usage, limitations, and suitability across a range of game genres.
Chapter 9
, Structuring Code with Behavioral Patterns – Template, Subclass Sandbox, and Type Object, explores the three most common structural patterns while building weapons classes in C++, which we will expand with Blueprint, exploring how the two languages can be used together.
Chapter 10
, Optimization through Patterns, dives into the key elements of optimization before releasing games by exploring the Dirty Flag, Data Locality, and Object Pooling design patterns.
To get the most out of this book
You will need a version of Unreal Engine 5 installed on your computer. All code examples have been tested on Unreal Engine 5.0.3, and they should work with later versions of the Engine. However, this may not be the case if Epic Games makes any major changes to the core engine.
If you are using the digital version of this book, we advise you to type the code yourself or access the code from the book’s GitHub repository (a link is available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.
We’ve included commented versions of the code found within the book as part of the GitHub repository, as opposed to including comments in the code samples, making the code easier to read and follow within the book.
Download the example code files
You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/Game-Development-Patterns-with-Unreal-Engine-5
. If there’s an update to the code, it will be updated in the GitHub repository.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/
. Check them out!
Conventions used
There are a number of text conventions used throughout this book.
Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: This also applies to the ScoreWidget class we will use to display the player’s score, which has been provided as part of the Chapter Resources folder.
A block of code is set as follows:
class APlayerController_CH7 : public APlayerController
{
public:
void Init();
protected:
UPROPERTY(EditAnywhere)
TSubclassOf
UPROPERTY(VisibleAnywhere, BlueprintReadOnly)
TObjectPtr
}
Bold: Indicates a new term, an important word, or words that you see on screen. For instance, words in menus or dialog boxes appear in bold. Here is an example: Enable the checkbox next to Editor symbols for debugging and click Apply.
Tips or important notes
Appear like this.
Get in touch
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, email us at [email protected]
and mention the book title in the subject of your message.
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata
and fill in the form.
Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com
.
Share Your Thoughts
Once you’ve read Game Development Patterns with Unreal Engine 5, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page
for this book and share your feedback.
Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.
Download a free PDF copy of this book
Thanks for purchasing this book!
Do you like to read on the go but are unable to carry your print books everywhere? Is your eBook purchase not compatible with the device of your choice?
Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost.
Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application.
The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily
Follow these simple steps to get the benefits:
Scan the QR code or visit the link below
Download a free PDF copy of this bookhttps://packt.link/free-ebook/9781803243252
Submit your proof of purchase
That’s it! We’ll send your free PDF and other benefits to your email directly
Part 1:Learning from Unreal Engine 5
In this part, we will be exploring Unreal Engine and the design patterns that are already included in the engine, or available to use as part of the many tools within the engine.
We will start by exploring Unreal Engine 5 and how it works with layers of code, before exploring a series of common mistakes that developers make when using Blueprint and seeing how to fix them. We will then discover a range of different patterns, exploring these with examples built from a mix of Blueprints and C++ and using a variety of tools, including World Partition and AI Behavior Trees.
This part has the following chapters:
Chapter 1
, Understanding Unreal Engine 5 and Its Layers
Chapter 2
, Hello Patterns
Chapter 3
, UE5 Patterns in Action – Double Buffer, Flyweight, and Spatial Partitioning
Chapter 4
, Premade Patterns in UE5 – Component, Behavior Tree, and Update Method
1
Understanding Unreal Engine 5 and its Layers
Design patterns are a series of tools and practices by which we can learn to write faster and easier-to-work-with code.
Applying design patterns to projects developed in Unreal Engine 5 (UE5) will allow you to make your projects more performant, easier to read, and build upon, as well as develop an improved understanding of how the engine works.
We’re going to begin by developing an understanding of the history of Unreal Engine and ensuring that we are all set up to work with the engine, covering some basic ideas of how C++ and Unreal Engine’s visual scripting language, Blueprint, are linked.
In this chapter, we’re going to cover the following main topics:
Introducing Unreal Engine 5
Installing Unreal Engine 5 and preparing your development environment
The Fuzzy
layer – bridging the gap from