Home Game Development Game Development Patterns with Unreal Engine 5

Game Development Patterns with Unreal Engine 5

By Stuart Butler , Tom Oliver
books-svg-icon Book
eBook $31.99 $21.99
Print $39.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $31.99 $21.99
Print $39.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Chapter 1: Understanding Unreal Engine 5 and its Layers
About this book
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 of this book, you’ll be proficient in designing systems with the perfect C++/Blueprint blend for maintainable and scalable systems.
Publication date:
January 2024
Publisher
Packt
Pages
254
ISBN
9781803243252

 

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 C++ to Blueprint
  • Translating back from Blueprint to C++
 

Technical requirements

Before embarking on this journey of discovery, know that this book will assume some working knowledge of C++ syntax and the Unreal Engine Editor. Familiarity with pointers and how to follow code in your chosen integrated development environment (IDE) will be key to understanding the Unreal core API.

You will require the following software:

  • Unreal Engine 5 (this book has been written with version 5.0.3).
  • Visual Studio is a decent free IDE (basic support for the engine is present, meaning projects may show errors and IntelliSense may not auto-complete some keywords, but the project will compile and run).
  • If you have access, JetBrains Rider version 2022 or later has built-in support for Unreal Engine, which will make the development process a lot easier. Rider is an alternative IDE to Visual Studio that is often preferred among programmers working with Unreal. It offers improved support for working with C++ in Unreal Engine, including auto-complete. You can learn more about it by visiting https://www.jetbrains.com/lp/rider-unreal/.
 

Introducing Unreal Engine 5

Unreal Engine 5, or Unreal for short, is a game engine developed by Epic Games. Unreal, as with any other game engine at its core, simply processes data from files and instructions into data that you can see on the screen. The suite of tools provided are designed to assist you in creative and predictable tasks. Having been created for you by elite programmers and designers, it is like outsourcing your development to the big leagues.

However, like a high-performance racing car driven by a learner, even the best tools can perform badly. The experts at Epic didn’t know how you would use their tools. So, when we design our code architecture, we need to keep this break in communications in mind. This is where this book comes in, teaching the expected best practices when writing games in Unreal Engine 5.

Unreal Engine has powered an impressive list of gaming titles covering a vast array of genres, shipping on a multitude of platforms.

Unreal Engine 3 powered some of the biggest hits from the seventh generation of game consoles, ranging from third-person shooter games such as the Gears of War series developed by Epic Games themselves to fighting games such as Injustice: Gods Among Us and Mortal Kombat from NetherRealm, as well as strategy games including the XCOM series developed by Firaxis Games.

The eighth generation of consoles saw Unreal Engine 4 expand its portfolio to include racing titles such as the MotoGP games from Milestone and Assetto Corsa Competizione from Kunos Simulazioni, as well as facilitating the hugely popular introduction of the Battle Royale genre with PlayerUnknowns’ Battlegrounds (PUBG Studios), which is listed as the fifth highest-selling video game on Wikipedia, and Epic GamesFortnite, which transitioned to Unreal Engine 5 in December 2021 as detailed in Chapter 3.

Unreal Engine 5 features a series of new, key technologies, including Nanite, a sub-mesh level of detail system allowing massive polycount models to render with even screen-space hull size at any distance, and Lumen, a real-time lighting solution that mixes mesh distance fields and atlassed local surface data progressively over time to create a realistic lighting effect at low cost. These new technologies drove the transition from 4.26/4.27 to 5.0 as part of a complete rework of Unreal’s rendering technology. The engine had an impactful debut with the release of The Matrix Awakens: An Unreal Engine Experience, a demo featuring photorealistic likenesses of Carrie-Anne Moss and Keanu Reeves, and an open-world city featuring impressive examples of crowd and traffic simulations.

Increasingly, games studios are opting to replace proprietary in-house developed game engines with Unreal Engine 5; studios such as CD Projekt Red (The Witcher) and Crystal Dynamics (Tomb Raider) have announced the decision to use Unreal Engine 5 in the latest installments of their game series.

Now that we’ve covered a little about Unreal Engine’s past, pedigree, and influence on gaming history, we will get things set up next so that you are ready to use Unreal Engine 5 with C++.

 

Installing Unreal Engine 5 and preparing your development environment

Unreal Engine can be downloaded either via the Epic Games Launcher (available from https://unrealengine.com, which will install the engine for you) or as source code from GitHub (www.github.com/EpicGames), allowing users to compile the engine and modify it to fit their projects.

To engage with the activities in this book, you won’t need to compile the engine from source unless you really want to. The benefits of compiling from source will likely come much later into your journey of working with Unreal Engine and C++. You will, however, need to install version 5.0.3 (or above) of the engine and have an IDE installed. This section covers the download, installation, and setup of the engine from scratch using the Unreal Launcher and installation of Visual Studio 2022 Community. If you already have the engine and Visual Studio installed, you can skip over this section.

Firstly, you will need to download the Launcher from https://unrealengine.com by clicking the Download button in the top-right corner of the page and clicking the Download Launcher button on the following page.

Once downloaded, you will need to install the Launcher from the .msi installer.

The Launcher is home to the Epic Games Store, your library of purchased and downloaded games as well as versions of Unreal Engine (4 and above). You will need to navigate to Unreal Engine and then Library, then click the yellow plus icon and select your engine version from the resulting engine slot:

Figure 1.1 – The default Epic Games Launcher with no versions of the engine installed

Figure 1.1 – The default Epic Games Launcher with no versions of the engine installed

Alternatively, if you don’t have any versions of the engine installed, you can click the yellow drop-down button in the top right of the Launcher application.

Both approaches will present you with the option of where you would like to install the engine. It is advisable to install the engine on an SSD if possible as the engine will load significantly quicker than from an HDD:

Figure 1.2 – Install location options

Figure 1.2 – Install location options

Clicking the Options button will present you with a series of optional elements for installing the engine:

Figure 1.3 – Installation options for Unreal Engine 5.0.3

Figure 1.3 – Installation options for Unreal Engine 5.0.3

We advise installing Starter Content, Templates and Feature Packs, and Engine Source.

Engine Source will make browsing and debugging code easier but does not allow you to rebuild the engine; for that functionality, you will need to download the source from GitHub, as mentioned earlier.

Editor symbols for debugging allows the debugging of C++ in the Editor. This is not required but will prove useful to facilitate jumping from the Editor to engine code and allow you to explore the code behind Blueprint nodes.

If you decide you want to add/remove elements later, you can modify these choices by clicking the down arrow next to Launch on the engine slot and selecting Options:

Figure 1.4 – Location of the Options menu on an engine slot

Figure 1.4 – Location of the Options menu on an engine slot

Enable the checkbox next to Editor symbols for debugging and click Apply.

Once you have the engine installed, you can move on to installing Visual Studio.

You will need to download the Visual Studio installer from https://visualstudio.microsoft.com/downloads/.

When you run the installer, select the Game Development with C++ preset in the Workloads tab and select optional components, as shown in Figure 1.5:

Figure 1.5 – Suggested installation options for Visual Studio Community 2022

Figure 1.5 – Suggested installation options for Visual Studio Community 2022

Once you have Visual Studio installed, you should be ready to go. If you want to further improve your experience of working in Visual Studio with Unreal Engine 5.0.X, you can find some additional guidance from Epic at https://docs.unrealengine.com/5.0/en-US/setting-up-visual-studio-development-environment-for-cplusplus-projects-in-unreal-engine/.

Now that we’ve installed the engine and set up our IDE, we can start exploring the link between C++ code and Blueprint.

 

The “Fuzzy” layer – bridging the gap from C++ to Blueprint

Most engines work on the concept of layers. Each layer has a specific job to do, and when stacked in the correct order, they simplify the development and maintenance of an engine. For example, if a new graphics language emerges that it would be wise to support, only the layer with the graphics pipeline needs to be changed.

There is no hard and fast rule for the number or breakdown of layers in an engine, but what you will generally find is a separation that resembles Table 1.1:

Tool

Full of Editor functions that speed up standard tasks. This suite is generally what an engine is marketed on.

Gameplay

All of the custom systems created to facilitate interaction mechanics that will be bespoke in the built game.

Function

Where all automatic internal systems are handled like input capture and physics processing, etc.

Resource

Memory management and asset streaming are handled here.

Platform

Essentially, the graphics pipeline definition and build platform native integrations if the engine supports it.

Base

Full of core dependency libraries such as UI frameworks for the Editor and math libraries.

Table 1.1 – Common engine layers and their uses

Although Unreal may not explicitly label its layers in this way, we can see them in action in the relationship between how Unreal processes C++ and Blueprint gameplay. Functions created with certain specifiers in C++ can be accessed in Blueprint, but the reverse is not true. This shows there is an order to our actions where signals can only be passed one way. We’ll refer to this internal separation between gameplay layers as the Fuzzy layer.

The fact that the Fuzzy layer exists places a limitation on how we design our systems, but in turn, we gain a separation that enables gameplay programmers to work alongside designers with little friction. Systems can be developed for simple creative use within accessible Blueprints with the more efficient C++ code hidden out of sight. To facilitate this construction, Unreal gives us Property Specifiers and Function Specifiers to define how signals will punch through.

Property Specifiers

Property Specifiers define characteristics of C++-defined variables when viewed and accessed in the Blueprint layer. The Unreal docs provide a handy table explaining the different levels of security afforded by each, along with some more specific ones designed for events, collections, and replication over networks (https://docs.unrealengine.com/5.0/en-US/unreal-engine-uproperties/). The six Display Property Specifiers most commonly used are as follows:

  • EditAnywhere – The value will be changeable in all class defaults and instance detail panels. This specifier is generally used while prototyping as it displays the variable in most places, with the most options for changing its value. However, security is the price paid for this flexibility, allowing any designer to change the default and instance values, and so access should be restricted down to what you actually need once a system is tested as working.
  • EditDefaultsOnly – The value will only be changeable in class defaults. Useful when a variable needs to be changed for balancing and all instances are spawned at runtime, where you wouldn’t have access to instance detail panels anyway. Can also be used to ensure no spawned instance has a rogue different value if necessary for execution.
  • EditInstanceOnly – The value will only be changeable in instance detail panels. Useful for allowing designers different values on bespoke placed actors in a scene but restricting the default value to something that is tested as working.
  • VisibleAnywhere – The value will be visible in all class defaults and instance detail panels, with no option for changing it from the Editor. This is useful for debugging how the initialization process affects a value when it is unknown if the code is generally wrong or wrong at an edge case. The latter will show incorrect values at the instance level, whereas the former will be wrong at both levels.
  • VisibleInstanceOnly – The value will only be visible in instance detail panels. Useful for surface-level debugging of values in each instance without cluttering the screen with debug messages when you have a large number of instances spawned.
  • VisibleDefaultsOnly – The value will only be visible in class defaults. Useful for designers to reference what a functional value is and create a parity in the visual elements of an actor. This is the highest security level as each actor will display the starting value in one place.

There are two access specifiers we need to pay attention to for now: BlueprintReadOnly and BlueprintReadWrite. They give child Blueprint-based classes access to either just the getter or both getter and setter in their graphs.

Function Specifiers

Function Specifiers work similarly to Property Specifiers, defining how functions should be seen and accessed by the Blueprint layer, with some subtleties to their usage. You can find a full list of Function Specifiers in the Unreal docs (https://docs.unrealengine.com/5.0/en-US/ufunctions-in-unreal-engine/), but the three we are interested in are detailed next:

  • BlueprintCallable – As the name suggests, Blueprint classes can call this function if it is in a parent class and it has the correct encapsulation type (public or protected).
  • BlueprintImplementableEvent – The stub for this function signature is defined in C++ without any implementation. This allows C++ systems to call it and Blueprint systems to fill out its actual body. You might use this for triggering visual effects like a laser beam on a gun when it is fired.
  • BlueprintNativeEvent – This allows C++ to define a function that is filled out in Blueprint, but in this case, there can also be a default implementation, which will also be run. Unreal achieves this by generating two more function definitions for you: *_Implementation() and Execute_*(). The former is used for the C++ side that must be run, and the latter is the function that must be called in C++ to fire both implementations.

Important note

As with layering, the C++ side of BlueprintNativeEvents will execute before the Blueprint side.

Using Property and Function Specifiers, we can make systems that cross the Fuzzy layer, but almost as important as routing function signals is designing inheritance hierarchies that smooth this process.

Useful inheritance

As standard practice, it is best to make sure that anything instanced in your world is a Blueprint class. This helps with debugging and linking classes with references as you have all the visual tools built into the Editor for tracing executions, and if classes are renamed or if they move directories, then links are live instead of text-based, preventing crashes.

To make this inheritance strategy work, it is recommended you think about your system from an abstract gameplay point of view. Which classes affect the mechanics? These classes need to have a C++ representation for efficiency, and so a hierarchy can be designed. From there, we inherit Blueprint classes from the end of each branch. This gives us the Blueprint classes to link, create instances of, and add visual components to:

Figure 1.6 – Example hierarchy for a weapon mechanic that includes both Projectile and HitScan mechanic types

Figure 1.6 – Example hierarchy for a weapon mechanic that includes both Projectile and HitScan mechanic types

In Figure 1.6, the C++ classes would contain all the logic for ammo, damaging actors, interaction handling, and so on. Then, in the Blueprint classes, components to display the mesh, run the kickback animations, and display the muzzle flash would be added. There would most likely be a function in the Weapon parent class called from somewhere in the firing logic that looks like this:

UFUNCTION(BlueprintImplementableEvent)
void Fire_Visuals();

This could then be implemented in the Blueprint classes to trigger visual effects. Using some of the patterns we will cover later, namely the type object pattern, you can create a vast array of weapons from these few classes with some simple asset and variable changes. This shows how the artist, designer, and programmer can all work together on one system without getting in each other’s way while still benefitting from the efficiency gain in C++.

In theory, this process is perfect, but theory rarely translates to the real world. A lot of dev time is usually spent working out how to do something based on forum posts, documentation, and videos. It’s great that these resources exist; almost every problem you come across has likely been solved by someone else, but there is no guarantee they have been developed with the same practice. You will come across a situation where the fix you need is in a Blueprint tutorial/example and your system needs it to be in C++, so let’s have a look at the translation process.

 

Translating back from Blueprint to C++

Equipping yourself with tools to translate back from Blueprint to C++ is the smart thing to do, not only for the everyday fixes as mentioned previously, but also for the triple-A setting in a large company. A typical Unreal mechanics development pipeline at a large studio might follow the following process:

  1. A designer has an idea for a mechanic and is given time to prototype it in Blueprint as a proof of concept.
  2. This mechanic is tested to see if it should be developed further.
  3. If it receives a green light, it will be a programmer’s job to convert the prototype into a more robust C++ system.

We’ve covered the tools for designing C++ systems to work with Blueprint effectively, but when faced with the aforementioned situation, how do you take another person’s vision and translate it into something that works efficiently yet doesn’t lose what made it good? Well, the obvious answer is to directly translate it. Node for node. That process is easy, as nodes in Blueprint are quite literally just C++ functions that you have to find in the engine source. Let’s take a closer look:

  1. The first step is to hover the mouse over the node. Every node has a Target class, and mousing over will tell you what that is.
  2. Next, we go to the Unreal Engine docs (https://www.unrealengine.com/en-US/bing-search?) and search for U< Target class name>::<Node name with no spaces>.
  3. The Unreal docs page for the function is likely to be bare, but it will give you the #include directory for the file header containing that function. Once a class has been included, it can be used and explored via autocompleting a dot accessor.

Important note

If the target is Actor, then it will have an A instead of a U at the beginning, as shown in the example in Figure 1.7. This is one of the oddities of UE5; each time there is one, it will be mentioned in a box like this.

Figure 1.7 – Showing the process from node to Unreal C++ documentation

Figure 1.7 – Showing the process from node to Unreal C++ documentation

This process may seem tedious but after a while of searching different things, you will start to see patterns and be able to work out where functions are likely to be. Each node with an execution pin (the white arrow) then becomes one line of code with input pins forming the function arguments, and output pins are generally the return type (multiple of which would form a struct).

Tip

Reading through the following headers will be useful for mastering the translation process as they are the most frequently used: AActor.h, UGameplayStatics.h, and UkismetSystemLibrary.h.

The next question is, how do you know where to leave the line between C++ and Blueprints? Theoretically, you could make everything in C++, but as we’ve already shown, that is not a good idea for teamworking reasons. The answer has already been hinted at, but generally, you want everything visual or not to do with the gameplay mechanics to be Blueprint-based. Where that line exactly sits is up to interpretation and not worth agonizing over.

Worked example

To cement this theory, let’s work through an example. In Figure 1.8, you can see an example Blueprint system designed to increment an integer when it is overlapped by a projectile; then, once it reaches 10 overlaps, it will play a sound and unhide a particle effect:

Figure 1.8 – A series of Blueprint nodes in a basic function; this piece of Blueprint has been arranged using a reroute node for readability but would normally be laid out more linearly

Figure 1.8 – A series of Blueprint nodes in a basic function; this piece of Blueprint has been arranged using a reroute node for readability but would normally be laid out more linearly

First, we need a C++ class for this to inherit from, and seeing as it is called BP_Target, we can name it Target. The Target class will need some variables; we can tell from the event that there is some kind of collision component named TargetCollision, which has its overlap event bound to this function. As a component, it needs to be stored in a pointer; otherwise, we would be referencing the class, not an instance. We also need an integer named TimesHit. As discussed prior, mechanics are made by a team of programmers, designers, and artists. Linking the right particle system for user feedback is a designer’s job, so we’ll leave that as Blueprint for now, but we do need a way to fire the Blueprint side, so a BlueprintImplementableEvent will be needed. With that in mind, the header for our new class will look something like this:

Target.h

#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "Target.generated.h"
class USphereComponent;
UCLASS(Abstract)
class EXAMPLE_API ATarget : public AActor
{
    GENERATED_BODY()
    UPROPERTY(EditDefaultsOnly)
    USphereComponent* _TargetCollision;
    int _TimesHit;
public:
    ATarget();
    UFUNCTION()
    void OnTargetCollisionBeginOverlap(AActor* OtherActor,
        int32 OtherBodyIndex, bool bFromSweep, const
        FHitResult& SweepResult);
    UFUNCTION(BlueprintImplementableEvent)
    Void TenHitVisuals();
};

Important note

Notice how the UCLASS() call includes the Abstract tag. This will stop designers from accidentally creating instances of your C++ classes that have not had any visuals set up.

The next step is to populate the function bodies:

Target.cpp

#include "Target.h"
#include "Components/SphereComponent.h"
#include "ExampleProjectile.h"
ATarget::ATarget()
{
    _TargetCollision =CreateDefaultSubobject <USphereComponent>
        (TEXT("TargetCollision"));
    _TargetCollision->SetupAttachment(RootComponent);
    _TargetCollision->
        OnComponentBeginOverlap.AddDynamic( this,
        &ATarget::OnTargetCollisionBeginOverlap);
    _TimesHit = 0;
}
void ATarget::OnTargetCollisionBeginOverlap
    (UPrimitiveComponent* OverlappedComponent, AActor*
        OtherActor, UPrimitiveComponent* OtherComp, int32
        OtherBodyIndex, bool bFromSweep, const FHitResult&
        SweepResult)
{
    ExampleProjectile* otherProj =
        Cast<AExampleProjectile>(OtherActor);
    if (otherProj != nullptr)
    {
        _TimesHit++;
        if (_TimesHit == 10)
        {
            TenHitVisuals();
        }
    }
}

The constructor is going to be standard, creating the default sub-object for the collision component and binding the overlap function to that component’s overlap event (OnTargetCollisionBeginOverlap). In the overlap function, the cast node becomes a cast to a temporary “cache” variable with an if statement to check its value against nullptr. _TimesHit can then post increment, and the branch converts to an if statement which, if passed, will call the BlueprintImplementableEvent to pass the signal to the Blueprint child class.

Note

You are not required to build this example; it is here for reference only.

There will be plenty more examples of Blueprint to C++ conversion throughout the rest of this book, but if you would like to see some first-party examples, the template projects created by Epic can be loaded in both C++ and Blueprint versions.

 

Summary

In this chapter, we have discussed what Unreal Engine 5 is and how to get it set up with a useful development environment. We also defined some of the key terms and tools we will be using in later chapters and shared a best practice strategy for building mechanics.

Lastly, we showed the process of translating from other practices to our new best practice.

This forms the foundation for designing well-structured systems. At this point, you should be able to at least plan mechanics for your game and implement something that utilizes both C++ and Blueprint.

In the next chapter, we will cover the process of optimizing a bad project by implementing some of the patterns we will see later in the book. This should give you an understanding of why design patterns are useful before we jump into a deep dive of each one.

Let’s end the chapter by answering a few questions to test our knowledge and cement some of these practices covered in the chapter.

 

Questions

  1. Which one of these describes the implementation of BlueprintNativeEvent?
    1. A function that can be described in Blueprint.
    2. A function defined in C++ with both C++ and Blueprint implementations.
    3. An event declared in C++ but used in Blueprint with an Execute function.
  2. How does Nanite work?
    1. Magic
    2. Mesh distance formulas
    3. Sub-mesh LOD groups
  3. Which one of these is not a Property Specifier?
    1. BlueprintWriteOnly
    2. EditInstanceOnly
    3. VisibleAnywhere
  4. Which base class adds an A to the start of each of its children in C++?
    1. GameplayStatics
    2. Actor
    3. ActorComponents
  5. All C++ functions should be marked as which of the following?
    1. BuildOnly
    2. Pure
    3. Abstract

Answers

  1. B
  2. C
  3. A
  4. B
  5. C
About the Authors
  • Stuart Butler

    Stuart Butler is an Unreal Engine Expert with over 13 years of experience in teaching Games 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 Authorised Instructor and Educational Content Creator who works with Epic Games on developing learning materials for Unreal Engine 5. Stuart holds a BSc (Hons) in Computer Games Design and a PgC in Higher and Professional Education.

    Browse publications by this author
  • Tom Oliver

    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, creating systems for games to mixed reality training simulations. Tom is the Course Leader for the BSc (Hons) Computer Games Design and Programming program 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 specialises in researching gameplay systems driven through mathematical phenomena.

    Browse publications by this author
Latest Reviews (1 reviews total)
Game Development Patterns with Unreal Engine 5
Unlock this book and the full library FREE for 7 days
Start now