Reader small image

You're reading from  Unreal Engine 5 Game Development with C++ Scripting

Product typeBook
Published inAug 2023
Reading LevelBeginner
PublisherPackt
ISBN-139781804613931
Edition1st Edition
Languages
Tools
Right arrow
Author (1)
ZHENYU GEORGE LI
ZHENYU GEORGE LI
author image
ZHENYU GEORGE LI

Zhenyu George Li is a passionate video game developer with 20+ years of experience. He has contributed significantly to many games and serves as a senior development consultant at Unity. His early immersion in technologies like C/C++, DirectX, OpenGL, and Windows GUI laid the foundation for his success. Notable titles in his portfolio include Magic Arena, Halo Infinity, Stela, Dead Rising 2, and The Bigs 2. He has gained extensive knowledge in programming, graphics, animation, gameplay, AI, multiplayer, and UI using Unreal and Unity engines. Additionally, he has taught UE at Vancouver Film School and has college teaching experience at College of Interactive Arts and Hefei Union University.
Read more about ZHENYU GEORGE LI

Right arrow

Learning How to Use UE Gameplay Framework Base Classes

Based on what you learned in the previous chapters, you should already know how to write C++ scripts for UE games and have an overall view of a typical UE C++ project structure. Now is the time to start learning basic C++ scripting skills in this chapter.

Games usually include a game environment, some actors (or game objects), and the interactions between the actors. Player characters are controlled by players, whereas non-player characters (NPCs) are controlled by game logic or artificial intelligence (AI) agents. In this chapter, you will learn how to derive base classes from Unreal Engine’s gameplay framework to create your own game actors and characters. Here, three game project configuration classes—PlayerController, GameMode, and GameInstance—are going to be introduced, which will help us to define the game’s specific players and rules.

Knowing the framework base classes is fundamental to...

Creating a Pangaea top-down game project

We believe that actually using what you have just learned to develop a real game is a very effective way for learners to quickly master new knowledge and skills.

Starting from this chapter, while still learning new C++ scripting skills, you will be working on a top-down game called Pangaea. The gameplay will involve controlling the main character running around the game map, killing enemies, and destroying enemy towers.

So, to get started, launch the UE5 editor from Epic Games Launcher:

Figure 5.1 – Steps to create the Pangaea project

Figure 5.1 – Steps to create the Pangaea project

Then perform the following steps to create the game project (see Figure 5.1):

  1. Select GAMES.
  2. Select Top Down.
  3. Choose C++.
  4. Choose the target directory (C:\UEProjects, for example).
  5. Input the project name, which is Pangaea.
  6. Then, click the Create button.

We have now created the game project. Let’s have an overall view of the most...

Understanding the gameplay framework base classes

Unreal Engine provides gameplay framework base classes for developers so that they can use and inherit from these base classes to create their new game-specific classes. Before utilizing the base classes, you need to understand the definitions of these classes as well as the relationships between them. The following class diagram will give you an overall view of the classes and the inheritance relationships:

Figure 5.2 – UE5 gameplay framework classes diagram

Figure 5.2 – UE5 gameplay framework classes diagram

From the diagram, you can see the following:

  • UObject is the ancestor class of all the remaining classes
  • AActor is the base class that is inherited by three groups of subclasses including the game actor (APawn), game information (AInfo), and player controller (AController) subclasses
  • UActorComponent is the base class for all the component classes
  • UGameInstance is a globally unique game instance manager class that can be extended...

Creating game actor classes

The term game actor classes refers to the AActor, APawn, and ACharacter classes. These three classes are used to instantiate game actors that will be placed in the game levels, as follows:

  • AActor is the base class for creating a wide range of objects, such as buildings, spawn points, portals, vehicles, characters, and so on. We will extend this class to create ADefenseTower, AWeapon, and AProjectile classes.
  • APawn is a subclass of AActor that is used to create non-character, player-controllable actors (not characters) that accept and react to player inputs—racing cars, for example.
  • ACharacter extends the APawn class for creating characters. A character can not only accept user inputs and moves but also has at least one skeletal mesh and the character state animations, such as idle, walk, run, attack, die, and so on. We will extend this class to create a new APlayerAvatar class.

Let’s practice creating the three important...

Recompiling C++ projects

Whenever you make changes to your C++ project, including code changes, adding new source files, and removing unused source files, you need to recompile the C++ project.

The simplest and most straightforward way is to click the Recompile and Reload button in the bottom-right corner of the UE editor:

Figure 5.8 – The Recompile and Reload button recompiles and reloads C++ code for game systems on the fly

Figure 5.8 – The Recompile and Reload button recompiles and reloads C++ code for game systems on the fly

Sometimes, this may not work because of the addition or removal of classes from the project. If this is the case, you can close the UE editor and build the project or the solution in Visual Studio.

If you manually delete source files in File Explorer, you should regenerate the Visual Studio project files before recompiling. To complete this task, find your Pangaea.uproject file in File Explorer, right-click on the .uproject file, and choose Generate Visual Studio project files from the pop-up menu:

Figure 5.9 – Generating Visual Studio project files ...

Using the UPROPERTY macro

The UPROPERTY macro is placed above the definition of standard C++ class variables to declare Unreal-recognized class properties. The UPROPERTY macro can have specifiers and metadata for different use cases.

The UPROPERTY syntax

Let’s take a look at the UPROPERTY syntax:

UPROPERTY([specifier1, specifier2, …], [meta(key1=value, key2=value2, … )]Type VariableName;

Let’s break it down:

  • As with function parameters, the specifiers and metadata are enclosed by a pair of parentheses
  • The square brackets are used to indicate that the enclosed content is optional
  • The ellipsis means that you can include more items
  • The metadata keys are only valid in the editor, and not for any game logic

Let’s look at two examples. The first example shows how to define a simple UPROPERTY variable:

UPROPERTY()bool bHasWeapon;

This example defines the bHasWeapon property without any specifiers and metadata...

Using the UFUNCTION macro

The UFUNCTION macro can be placed above the line of standard C++ function declarations. As with the UPROPERTY macro, UFUNCTION also has its specifiers and metadata to interpret the use of the functions.

The UFUNCTION syntax

Let’s first check out the UFUNCTION syntax:

UFUNCTION([specifier1, specifier2, …], [meta(key1=value,   key2=value2, … )]ReturnType FunctionName([param1, param2, …]) [const];

Let’s break it down:

  • The square brackets are used to indicate that the enclosed content is optional
  • The ellipsis means that you can include more items
  • The metadata keys are only valid in the editor, not for any game logic

The following example demonstrates how to mark the GetHealthPoints() function to be a UFUNCTION macro with a displayname value of Get HP:

UFUNCTION(BlueprintCallable, Category="Player Avatar",  Meta=(DisplayName="Get HP"))
int GetHealthPoints...

Adding components to the new actors

Unreal provides useful components that can be added to actors; for example, you can add a static mesh component to an actor so that the actor is visually represented in the game levels. In our case, we want to add a box collision component and a static mesh component to ADefenseTower and AProjectile, as follows:

  • UBoxComponent: This is added as the actor’s root component for collision detection
  • UstaticMeshComponent: This is added as the child of the actor’s root component, which allows us to select and display a 3D mesh in the game levels

To use these two components, you should include their header files at the beginning of ADefenseTower.h and AProjectile.h files.

Including component header files

The order of #include statements in C++ is not a big concern, but you should ensure that the *.generated.h statement is placed as the last include statement and right before the UCLASS definition.

Here is the example...

Creating blueprints from the new actor classes

You may wonder why we would want to create Blueprint classes even after having C++ actor classes. The answer is in finding the right balance.

While it is totally acceptable to create actor classes solely with C++, particularly to increase performance, there is a trade-off involved—by exclusively relying on C++, you sacrifice the flexibility provided by blueprints. On the other hand, utilizing blueprints to handle relatively simple and editable data settings proves to be a more advantageous choice. It allows for easier tweaking and iteration without requiring code changes.

Thus, combining the power of both C++ and blueprints enables us to strike the ideal balance between performance, complexity, and flexibility in game development.

For instance, a character class for the initial settings and display meshes for different characters may vary; in such a scenario, it would be much easier and less work to edit them in the Blueprint...

Learning about the Unreal gameplay framework classes

The Unreal gameplay framework includes four classes, PlayerController, GameModeBase, GameState, and GameInstance, playing vital roles in managing various aspects of gameplay and overall game functionality. The first two classes are usually created automatically when a project is generated, while the remaining classes need to be manually added to the project.

Locating and creating gameplay framework classes in Pangaea

If you go to the All | C++ Classes | Pangaea folder, you should find that the project already has PangaeaGameMode and PangaeaPlayerController classes (see Figure 5.16). These two classes were created when the game project was initiated:

Figure 5.16 – The existing PangaeaGameMode and PangaeaPlayerController C++ classes

Figure 5.16 – The existing PangaeaGameMode and PangaeaPlayerController C++ classes

PangaeaPlayerController inherits from PlayerController, and PangaeaGameMode inherits from GameModeBase.

In addition to the existing PangaeaGameMode and PangaeaPlayerController...

Using the Cast template function

Unreal Engine is designed as a universal graphics development tool. It provides base classes that can be inherited for developing specific games. That means the standard functions can only return the base type results, and game developers are responsible for casting the results to the specific types defined in their games.

In Unreal, Cast is a safe conversion function used for casting data types. Here is the syntax:

ToType* Cast<ToType>(FromType* theObjectPointerOfFromType)

Let’s break the syntax down:

  • ToType represents the target type that you want to get after the conversion
  • FromType represents the original type that you want to convert from
  • The angular brackets (< and >) are C++ template expressions
  • The function returns nullptr if the casting operation failed

In C++, a function can be declared to be generic with a template expression, which means that the function can accept and process different...

Summary

Throughout this chapter, you learned about Unreal Engine’s basic gameplay framework classes, including AActor, APawn, ACharacter, APlayerController, AGameModeBase, AGameStateBase, and UGameInstance. By extending these classes, you can create the most needed elements for developing new games. Besides creating game actors, two important macros, UPROPERTY and UFUNCTION, were also introduced so that you can make actor properties and functions recognizable and work together with the engine. Your new classes’ data can also be edited in the engine editor.

In this chapter, the following tasks were completed to enhance the game development process in Pangaea. New classes, including DefenseTower, Projectile, and PlayerAvatar, were created by inheriting from the Actor and Character classes. These classes were enriched with additional properties and functions to provide customization and unique behaviors.

Different methods for rebuilding uprojects after code changes...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Unreal Engine 5 Game Development with C++ Scripting
Published in: Aug 2023Publisher: PacktISBN-13: 9781804613931
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at AU $19.99/month. Cancel anytime

Author (1)

author image
ZHENYU GEORGE LI

Zhenyu George Li is a passionate video game developer with 20+ years of experience. He has contributed significantly to many games and serves as a senior development consultant at Unity. His early immersion in technologies like C/C++, DirectX, OpenGL, and Windows GUI laid the foundation for his success. Notable titles in his portfolio include Magic Arena, Halo Infinity, Stela, Dead Rising 2, and The Bigs 2. He has gained extensive knowledge in programming, graphics, animation, gameplay, AI, multiplayer, and UI using Unreal and Unity engines. Additionally, he has taught UE at Vancouver Film School and has college teaching experience at College of Interactive Arts and Hefei Union University.
Read more about ZHENYU GEORGE LI