Unreal Engine 4.x Scripting with C++ Cookbook - Second Edition

3 (2 reviews total)
By John P. Doran , William Sherif , Stephen Whittle
    Advance your knowledge in tech with a Packt subscription

  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. UE4 Development Tools

About this book

Unreal Engine 4 (UE4) is a popular and award-winning game engine that powers some of the most popular games. A truly powerful tool for game development, there has never been a better time to use it for both commercial and independent projects. With more than 100 recipes, this book shows how to unleash the power of C++ while developing games with Unreal Engine.

This book takes you on a journey to jumpstart your C++ and UE4 development skills. You will start off by setting up UE4 for C++ development and learn how to work with Visual Studio, a popular code editor. You will learn how to create C++ classes and structs the Unreal way. This will be followed by exploring memory management, smart pointers, and debugging your code. You will then learn how to make your own Actors and Components through code and how to handle input and collision events. You will also get exposure to many elements of game development including creating user interfaces, artificial intelligence, and writing code with networked play in mind. You will also learn how to add on to the Unreal Editor itself.

With a range of task-oriented recipes, this book provides actionable information about writing code for games with UE4 using C++. By the end of the book, you will be empowered to become a top-notch developer with UE4 using C++ as your scripting language!

Publication date:
March 2019


UE4 Development Tools

In this chapter, we will outline some basic recipes for getting started in Unreal Engine 4 (UE4) game development, and the basic tools that we will use for creating the code that makes our game. This will include the following recipes:

  • Installing Visual Studio
  • Creating and building your first C++ project in Visual Studio
  • Changing the code font and color in Visual Studio
  • Extension – changing the color theme in Visual Studio
  • Formatting your code (Autocomplete settings) in Visual Studio
  • Shortcut keys in Visual Studio
  • Extended mouse usage in Visual Studio
  • UE4 – installation
  • UE4 – first project
  • UE4 – creating your first level
  • UE4 – hot reloading
  • UE4 – logging with UE_LOG
  • UE4 – making an FString from FStrings and other variables


Creating a game is an elaborate task that will require a combination of assets and code. To create assets and code, we'll need some pretty advanced tools, including art tools, sound tools, level-editing tools, and code-editing tools. In this chapter, we'll discuss finding suitable tools for asset creation and coding. Assets include any visual artwork (2D sprites, 3D models), audio (music and sound effects), and game levels. Code is the text (usually C++) that instructs the computer on how to tie these assets together to make a game world and level, and how to make that game world play. There are dozens of very good tools for each task; we will explore a couple of each, and make some recommendations. Game editing tools, especially, are hefty programs that require a powerful CPU and lots of memory, and very good, ideal GPUs for good performance. Protecting your assets and work is also a necessary practice. We'll explore and describe source control, which is how you back up your work on a remote server. An introduction to UE4 programming is also included, and we will also explore basic logging functions and library use. Significant planning is also required to get these tasks done, so we'll use a task planner software package to do so.


Technical requirements

As listed on UE4's FAQs page, it is recommend to have a a desktop PC with Windows 7 64-bit or a Mac with macOS X 10.9.2 or later, 8 GB of RAM, a quad-core Intel or AMD processor, and a DX11-compatible video card. UE4 will run on desktops and laptops below these recommendations, but performance may be limited.

For those using a Mac computer, Visual Studio for Mac currently does not support C++. You'll need to use a different IDE, such as Visual Studio Code or Xcode, instead.


Installing Visual Studio

Visual Studio is an essential package for code editing when editing the C++ code for your UE4 game.

Getting ready

We're going to set up a C++ coding environment to build our UE4 applications. We'll download Visual Studio 2017, install it, and set it up for UE4 C++ coding.

How to do it...

  1. Begin by visiting https://www.visualstudio.com/en-us/products/visual-studio-community-vs.aspx. Click on Download VS Community 2017. This downloads the ~1,250 KB loader/installer:
You can compare editions of Visual Studio at https://visualstudio.microsoft.com/vs/compare/. The Community Edition of Visual Studio is fully adequate for UE4 development purposes in this book, that is, as long as you're an individual developer, doing academic research, or have fewer than six people on your team.
  1. Launch the installer, and continue through the installer until you get to the window where you select the components of Visual Studio 2017 that you want to add to your PC. Keep in mind that the more features you select, the larger your installation will be.
  1. Support for C++ is now an optional part of Visual Studio and isn't installed by default, so we have to select that we want it installed. Under the Workloads section, scroll down to the Mobile and Gaming heading and check the Game development with C++ option:
It is possible to download the Unreal Engine installer at this point as well by selecting it under the Optional section in the Installation details menu, but we will be getting the latest version of the Epic Games launcher and Unreal Engine directly from Epic Games in a separate recipe later on in this chapter.
  1. After you have selected the tools you'd like to add on to Visual Studio, click the Install button. The installer tool will download the required components and continue setup. After finishing installation, the installer may ask you to restart your computer. Go ahead and do so.
  2. After you download and install Visual Studio 2017, launch it. You will be presented with a Sign in dialog box:

You can Sign in with your Microsoft account (the one you use to sign into Windows 10) or Sign up for a new account. After you've signed in or signed up, you will be able to sign into Visual Studio itself. It may seem odd to sign into a desktop code editing program, but your sign-in will be used for source control commits to your repositories. On first signing into Visual Studio, you can select (one time only) a unique URL for your source code repositories, as hosted on Visualstudio.com (https://visualstudio.microsoft.com/).

How it works...


Creating and building your first C++ project in Visual Studio

In order to compile and run code from Visual Studio, it must be done from within a project.

Getting ready

In this recipe, we will identify how to create an actual executable running program from Visual Studio. We will do so by creating a project in Visual Studio to host, organize, and compile the code.

How to do it...

In Visual Studio, each group of code is contained within something called a Project. A project is a buildable conglomerate of code and assets that produce either an executable (.exe runnable) or a library (.lib or .dll). A group of projects can be collected into something called a Solution. Let's start by constructing a Visual Studio solution and a project for a console application, followed by constructing a UE4 sample project and solution:

  1. Open Visual Studio and go to File | New | Project....
  2. You will see a dialog, as follows:
  1. Select Visual C++ in the pane on the left-hand side. In the middle pane, hit Windows Console Application. Name your project in the lower box, and then hit OK:

Once the application wizard completes, you will have created your first project. Both a solution and a project will be created.

  1. To see these, you need Solution Explorer. To ensure that Solution Explorer is showing, go to View | Solution Explorer (or press Ctrl + Alt + L). Solution Explorer is a window that usually appears docked on the right-hand side of the main editor window, as shown in the following screenshot:
Solution Explorer location
It is possible to arrange your layout however you like inside Visual Studio. If you ever want to go back to the default layout, you can go to Window | Reset Window Layout.

The Solution Explorer also displays all the files that are part of the project. This default solution already contains a few files, and we can add and remove new files in this section from here. As your project grows, more and more files are going to be added to your project. In the Source Files folder, you'll also notice a file created called FirstProject.cpp, which will look as follows:

// FirstProject.cpp : This file contains the 'main' function. Program execution begins and ends there.

#include "pch.h"
#include <iostream>

int main()
std::cout << "Hello World!\n";

// Run program: Ctrl + F5 or Debug > Start Without Debugging menu
// Debug program: F5 or Debug > Start Debugging menu

// Tips for Getting Started:
// 1. Use the Solution Explorer window to add/manage files
// 2. Use the Team Explorer window to connect to source control
// 3. Use the Output window to see build output and other messages
// 4. Use the Error List window to view errors
// 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project
// 6. In the future, to open this project again, go to File > Open > Project and select the .sln file
  1. Press Ctrl + Shift + B to build the project, then Ctrl + F5 to run the project.
  1. Your executable will be created, and you will see a small black window with the results of your program's run:

How it works...

Building an executable involves translating your C++ code from text language into a binary file. Running the file runs your game program, which is just the code text that occurs in the main() function between { and }.

There's more...

Build configurations are styles of build that we will discuss here. There are at least two important build configurations you should know about: Debug and Release. The Build configuration that's currently selected is at the top of the editor, just below the toolbar in the default position:

Location of the currently selected Build Configuration

Depending on which configuration you select, different compiler options are used. A Debug configuration typically includes extensive debug information in the build, as well as the ability to turn off optimizations to speed up compilation. Release builds are often optimized (either for size or for speed) and take a bit longer to build; they result in smaller or faster executables. Stepping through a file's behavior by moving through with the debugger line by line is often better in the Debug mode than the Release mode.


Changing the code font and color in Visual Studio

Customizing the font and color in Visual Studio is not just about flexibility. Due to monitor resolutions being too high or low, it may become a necessity!

Getting ready

Visual Studio is a highly customizable code editing tool. You might find the default fonts too small for your screen. This is easily adjustable by holding down the Ctrl key and using the mouse wheel to increase or decrease the size, but you may want to change the default value. Or, perhaps you may want to have more control, as you may want to change your code's font size and color. You may also want to completely customize the coloration of keywords and the text background colors. The Fonts and Colors dialog box, which we'll show you how to use in this section, allows you to completely customize every aspect of the code editor's font and color:

How to do it...

  1. From within Visual Studio, go to Tools | Options...:
  1. Select Environment | Fonts and Colors from the dialog that appears. It will look like what's shown in the following screenshot:
  1. Play around with the font and font size of Text Editor/Plain Text. Click OK on the dialog, and see the results in the code-text editor:
Modified font and colors

Text Editor/Plain Text describes the font and size that's used for all code text within the regular code editor. If you change the size of the font, the size changes for any text that's entered into the coding window (for all languages, including C, C++, C#, and others).

To return to what the menu has by default based on your theme, click on the Use Defaults button to the right of the Show Settings for: option.

The color (foreground and background) is completely customizable for each item. Try this for the Text Editor/Keyword setting (affects all languages), or for items specific to C++, such as Text Editor/C++ Functions. Click OK, and you will see the changed color of the item reflected in the code editor.

You may also want to configure the font size of the Output Window, under the Show settings for: option, so click on the drop-down and select Output Window, as shown in the following screenshot:

The Output Window is the little window at the bottom of the editor that displays build results and compiler errors.

You can't save-out (export) or bring in (import) your changes to the Fonts and Colors dialog. But you can use something called the Visual Studio Theme Editor Extension. To learn more, refer to the Extension – changing the color theme in Visual Studio recipe of this chapter, to learn how to export and import customized color themes.

For this reason, you may want to avoid changing font colors from this dialog. You must use this dialog to change the font and font size, however, for any setting (at the time of writing).

How it works...

The Fonts and Colors dialog simply changes the appearance of code in the text editor as well as for other windows, such as the output window. It is very useful for making your coding environment more comfortable.

There's more...

Once you have customized your settings, you'll find that you may want to save your customized Fonts and Colors settings for others to use, or to put into another installation of Visual Studio, which you have on another machine. Unfortunately, by default, you won't be able to save-out your customized Fonts and Colors settings. You will need something called the Visual Studio Theme Editor extension to do so. We will explore this in the next recipe.

See also

  • The Extension – changing the color theme in Visual Studio recipe describes how to import and export color themes

Extension – changing the color theme in Visual Studio

By default, you cannot save the changes you make to the font colors and background settings that you make in the Fonts and Colors dialog. To fix this issue, Visual Studio has a feature called Themes. If you go to Tools | Options | Environment | General, you can change the theme to one of the three pre-installed stock themes (Light, Blue, and Dark):

A different theme completely changes the look of Visual Studio, from the colors of the title bars to the background color of the text editor window.

You can also customize the theme of Visual Studio completely, but you'll need an extension to do so. Extensions are little programs that can be installed into Visual Studio to modify its behavior.

By default, your customized color settings cannot be saved or reloaded into another Visual Studio installation without the extension. With the extension, you will also be able to save your own color theme to share with others. You can also load the color settings made by another person or by yourself into a fresh copy of Visual Studio.

How to do it...

  1. Go to Tools | Extensions and Updates....
  2. From the dialog that appears, choose Online in the panel on the left-hand side. Start typing Theme Editor into the search box on the right. The Color Theme Editor for Visual Studio option will pop up in your search results:
  1. Click the small Download button in the top right-hand corner of the entry. Click through the installation dialog prompts, allowing the plugin to install. You'll then notice on the bottom of the window that it is scheduled for installation but will wait until Visual Studio is closed.
  1. Close the window and Visual Studio, saving our project. After our program has closed, the VSIX Installer window will come up to confirm that you want to install the software. Click on the Modify button and it should start:
Alternatively, visit https://marketplace.visualstudio.com/items?itemName=VisualStudioPlatformTeam.VisualStudio2017ColorThemeEditor and download/install the extension by double-clicking the .vsix file that comes from your browser.
  1. Once it has finished installing, open up Visual Studio again and open our project. One of the quickest ways to do so is from the Recent section on the Start Page:
  1. After restarting, go to Tools | Customize Colors to open the Color Themes editor page:
The Color Themes editor page
  1. From the Color Themes dialog that appears, click on the little palette-shaped icon on the upper-right corner of the theme that you want to use as your base or starting theme (I've clicked on the palette for the Light theme here, as you can see in the following screenshot):
  1. A copy of the theme will appear in the Custom Themes section in the lower part of the Color Themes window. Click on Edit Theme to modify the theme that is the middle button that appears when you hover over the custom theme. When you are editing the theme, you can change everything from the font text color to the C++ keyword color.
  1. The main area you are interested in is the C++ Text Editor section. To gain access to all the C++ Text Editor options, be sure to select the Show All Elements option at the top of the Theme Editor window, as shown in the following screenshot:
Be sure to select the Show All Elements option in the Theme Editor window to show text editor settings specific to C++. Otherwise, you'll be left with only Chrome/GUI-type modifications being possible.
  1. Note that, while most of the settings you are interested in will be under Text Editor | C/C++, some will not have the C++ subheading. For example, the setting for the main/plain text inside the editor window (for all languages) is under Text Editor | Plain Text (without the C++ subheading).
  1. Select the theme to use from Tools | Options | Environment | General. Any new themes you have created will appear automatically in the drop-down menu.

How it works...

Once we load the plugin, it integrates into Visual Studio quite nicely. Exporting and uploading your themes to share with others is quite easy too.

Adding a theme to your Visual Studio installs it as an extension in Tools | Extensions and Updates.... To remove a theme, simply Uninstall its extension:


Formatting your code (Autocomplete settings) in Visual Studio

Code-writing formatting with Visual Studio is a pleasure. In this recipe, we'll discuss how to control the way Visual Studio lays out the text of your code.

Getting ready

Code has to be formatted correctly. You and your co-programmers will be able to better understand, grok, and keep your code bug-free if it is consistently formatted. This is why Visual Studio includes a number of auto-formatting tools inside the editor.

How to do it...

  1. Go to Tools | Options. Once there, go to the Text Editor | C/C++ section and select it. This dialog displays a window that allows you to toggle Automatic brace completion:

Automatic brace completion is a feature where, when you type {, a corresponding } is automatically typed for you. This feature may irk you if you don't like the text editor inserting characters for you unexpectedly.

You generally want Auto list members on, as that displays a nice dialog with the complete names of data members listed for you as soon as you start typing. This makes it easy to remember variable names, so you don't have to memorize them:

If you press Ctrl + spacebar inside the code editor at any time, the auto list pops up.
  1. Some more autocomplete behavior options are located under Text Editor | C/C++ | Formatting:

I recommend using all of the options at first and then disabling them only if they interrupt your workflow.

You can also autoformat a section of text by highlighting a section of text and selecting Edit | Advanced | Format Selection (Ctrl + K, Ctrl + F).

How it works...

The default autocomplete and autoformat behaviors may irk you. You need to converse with your team on how you want your code to be formatted (spaces or tab indents, size of indent, and so on), and then configure your Visual Studio settings accordingly.


Shortcut keys in Visual Studio

There are a number of shortcut keys that will make coding and project navigation much faster and more efficient for you. In this recipe, we will describe how to use some of the common shortcut keys that will really enhance your coding speed.

Getting ready

To get started, you will need to have Visual Studio installed and a project opened to look at the features.

How to do it...

The following are some very useful keyboard shortcuts for you to try:

  1. Click on one part of the code, then click somewhere else, at least 10 lines of code away. Now, press Ctrl + - [navigate backwards]. Navigation through different pages of source code (the last place you were at, and the place you are at now) is done by pressing Ctrl + - and Ctrl + Shift + -, respectively:

Note that the being mentioned is the one near the 0 key on your keyboard and will not work with the on the numpad.

Warping around in the text editor using Ctrl + -. The cursor will jump back to the last location it was in that is more than 10 lines of code away, even if the last location was in a separate file.

Say, for example, you're editing code in one place, and you want to go back to the place you've just been (or go back to the section in the code you came from). Simply press Ctrl + -, and that will warp you back to the location in the code you were at last. To warp forward to the location you were at before, press Ctrl + -, press Ctrl + Shift + -. To warp back, the previous location should be more than 10 lines away, or in a different file. These correspond to the forward and back menu buttons in the toolbar:

The back and forward navigation buttons in the toolbar correspond to the Ctrl + - and Ctrl + Shift + - shortcuts, respectively.
  1. Press Ctrl + W to highlight a single word.
  2. Press and hold Ctrl + Shift + right arrow (or left arrow) (not Shift + right arrow) just to move to the right and left of the cursor, selecting entire words.
  3. Press Ctrl + C to copy text, Ctrl + X to cut text, and Ctrl + V to paste text.
  1. Clipboard ring: The clipboard ring is a kind of a reference to the fact that Visual Studio maintains a stack of the last copy operations. By pressing Ctrl + C, you push the text that you are copying into an effective stack. Pressing Ctrl + C a second time on different text pushes that text into the Clipboard Stack. For example, in the following diagram, we pressed Ctrl + C on the word cyclic first, then Ctrl + C on the word paste afterward.

As you know, pressing Ctrl + V pastes the top item in the stack. Pressing Ctrl + Shift + Insert accesses a very long history of all the items ever copied in that session, that is, items underneath the top item in the stack. After you exhaust the list of items, the list wraps back to the top item in the stack. This is an odd feature, but you may find it useful occasionally.

  1. Ctrl + M collapses a code section:

How it works...

Keyboard shortcuts allow you to speed up work in the code editor by reducing the number of mouse- reaches that you have to perform in a coding session.


Extended mouse usage in Visual Studio

The mouse is a pretty handy tool for selecting text. In this section, we'll highlight how to use the mouse in an advanced way so that you can make quick edits to your code's text.

How to do it...

  1. Hold down the Ctrl key while clicking to select an entire word:
  1. Hold down the Alt key to select a box of text (Alt + left-click + drag):

You can then either cut, copy, or overwrite the box-shaped text area; in the latter case, the characters you type will be repeated in all selected rows.

How it works...

Mouse-clicking alone can be tedious, but with the help of Ctrl + Alt, it becomes quite cool.


Installing Unreal Engine 4 (UE4)

There are a number of steps to follow to install and configure UE4 properly. In this recipe, we'll walk through the correct installation and setup of the engine.

Getting ready

UE4 takes up quite a few GB of space, so you should have at least 20 GB or so free for the installation on the target drive. Note that every project is also at least 1 GB as well, so you will need more space on your computer (or an additional hard drive) for more projects you wish to create.

How to do it...

  1. Visit unrealengine.com in your web browser of choice:
  1. On the top-right corner of the screen, click on the Download button. You'll then be asked to create an Epic Games account. If you already have one, you can scroll down to the bottom of the screen and click the Sign in option.
  2. Run the installer for the Epic Games Launcher program by double-clicking the EpicGamesLauncherInstaller-x.x.x-xxx.msi installer. Install it in the default location.
  3. Once the Epic Games Launcher program is installed, open it by double-clicking its icon, which can be found on your desktop or in the Start menu:
  1. You'll need to sign in with the same login information you created or used earlier, and then you'll arrive at the main page of the launcher:
  1. There are a lot of available options, but we want to click on the Unreal Engine option on the top-left of the screen.
  2. Browse the start page and take a look around. Eventually, you will need to install an engine. Click on the large orange Install Engine button on the screen, as shown in the following screenshot:
  1. A pop-up dialog will ask you to agree to an End Licence Agreement. Afterwards, you'll be asked to choose an install location. Then, click the Install button:

The launcher will start downloading the engine. It is about 7 GB, so it may take a while. Once finished, your screen should look something like this:

After the engine has installed, the Install Engine button will change to a Launch Engine button.

How it works...

The Epic Games Launcher is the program that you need to start up the engine itself. It keeps a copy of all your projects and libraries in the Library tab.

There's more...

As you learn more about working in UE4, you should check out some of the free library packages in the Library | Vault section. For that, click the Library item on the left-hand side and scroll down until you see Vault, underneath My Projects.


Creating your first project in UE4

Setting up a project within UE4 takes a number of steps. It is important to get your options correct so that you can have the setup that you like, so carefully follow this recipe when constructing your first project.

Each project that you create within UE4 takes up at least 1 GB of space or so, so you should decide whether you want your created projects on the same target drive or on an external or separate HDD.

How to do it...

  1. From the Epic Games Launcher, click on the Launch Unreal Engine 4.21.2 button on the left side of the screen. Once you are inside the engine, an option to create a new project or load an existing one will present itself.
Note that depending on when you are reading this book, the version number could be different, but the steps should be the same, if not incredibly similar.
  1. Select the New Project tab.
  2. Decide whether you will be using C++ to code your project, or blueprints exclusively:
  • If you're using blueprints exclusively, make your selection of a template to use from the Blueprint tab.
  • If you're using C++ in addition to blueprints to construct your project, select the project template to construct your project based on the C++ tab.
  • If you're not sure what template to base your code on, Basic Code is an excellent starting point for any C++ project (or Blank for a blueprint-exclusive (Unreal's built-in visual scripting language) project):

For the purpose of this book, we will always be using a C++ project:

  1. Take a look at the three icons that appear beneath the template listing. There are three options here to configure:
  • You can choose to target desktop or mobile applications.
  • You have an option to alter the quality settings (the picture of a plant with the sun above it), but you probably don't need to alter these. The quality settings are reconfigurable under Engine | Engine Scalability Settings anyway.
  • The last option is whether to include Starter Content with the project or not. You can probably use the Starter Content package in your project. It has some excellent materials and textures available within it that are invaluable for a beginner, but as you start creating your own advanced projects, you will likely no longer need it.

If you don't like the Starter Content package, try the packages in the UE4 Marketplace. There is some excellent free content there, including the GameTextures Material Pack.
  1. Select the drive and folder in which you will save your project. Keep in mind that each project is roughly 1 GB in size, and you will need at least that much space on the destination drive.
  2. Name your project. Preferably, name it something unique and specific to what you are planning on creating.
  3. Hit Create. Both the UE4 Editor and Visual Studio 2017 windows should pop up, enabling you to edit your project.
In the future, keep in mind that you can open the Visual Studio 2017 Solution using one of two methods. The first is using your local file explorer. Navigate to the root of where your project is stored and double-click on the ProjectName.sln file. The second way is from UE4: click on File | Open Visual Studio.

Creating your first level in UE4

Creating levels in UE4 is easy and facilitated by a great all-around UI. In this recipe, we'll outline basic editor usage and describe how to construct your first level once you have your first project launched.

Getting ready

Complete the previous recipe, Creating your first project in UE4. Once you have a project constructed, we can proceed with creating a level.

How to do it...

  1. The default level that gets set up when you start a new project will contain some default geometry and scenery if the starter content was included when creating the project:
The MinimalDefault level and interface of Unreal Engine 4

You don't need to start with this starter stuff, however. If you don't want to build from it, you can delete it, or create a new level.

  1. To create a new level, click File | New Level...:

From here, you can select to create a level with a background sky (Default), or without a background sky (Empty Level).

If you choose to create a level without a background sky, keep in mind that you must add a light to it to see the geometry you add to it.
  1. If you loaded the Starter Content on your project's creation (or some other content), then you can use the Content Browser to pull content into your level. Simply drag and drop instances of your content from the Content Browser into the level and save it, and then play the game by hitting the Play button.
  2. Add some geometry to your level using the Modes panel (Window | Modes). Be sure to click on the left-most button with the picture of a light bulb and cube on it to access the placeable geometry:

By default, the Basic option is selected, which contains general geometry and other common features that are needed in Unreal. You can also add lights via the Modes tab by clicking on the Lights subtab on the left-hand side of the Modes tab. These can be added to a level by dragging and dropping as well.

The Modes panel contains two useful items for level construction: some sample geometry to add (cubes and spheres and the like), as well as a panel full of lights. Try these out and experiment to begin laying out your level.
If you are interested in learning more about building levels inside Unreal Engine, check out https://docs.unrealengine.com/en-us/Engine/QuickStart

UE4 – hot reloading

When you created a new Unreal Engine 4 C++ project, you saw that both Visual Studio and Unreal Engine 4 opened up. In this recipe, we will go through an example of modifying a script in Visual Studio and then compiling the code to see the changes.

Getting ready

To see the effects of changing one of the classes, we have to actually be using the class. Unreal automatically creates one of these classes for us by default (AChapter01_GameModeBase), so for this simple example, we will make use of it.

Note that everywhere you see Chapter01 in the recipes in this chapter, I am referring to the project name, and if yours is named differently, you may see different text.
  1. From the Unreal Editor, go to Edit | Project Settings. Select the Maps & Modes option under the Project section.
  2. Under Default GameMode, select Chapter01_GameMode:
Note that the class name is AChapter01_GameModeBase in code, while in Unreal's menus it doesn't have the A. This is because Unreal's naming convention for classes always adds an A to classes that inherit from the Actor class. We will discuss this in greater detail later on in this book.

A game mode is a class that will contain the rules of your game type.

For more information on game modes, check out https://docs.unrealengine.com/en-US/Gameplay/Framework/GameMode.

How to do it...

  1. Inside Visual Studio under the Solution Explorer, you will see a number of pre-created files. Open the Games/Chapter_01/Source/Chapter_01 folder and you should see the Chapter01GameModeBase.h and .cpp files. Double-click on the .h file to open it:
  1. Add the following code (in bold) to the file:
// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

#include "CoreMinimal.h"
#include "GameFramework/GameModeBase.h"
#include "Chapter_01GameModeBase.generated.h"

class CHAPTER_01_API AChapter_01GameModeBase : public AGameModeBase
void BeginPlay();

  1. Next, open the .cpp file and update it to have the following:
// Fill out your copyright notice in the Description page of Project Settings.

#include "Chapter_01GameModeBase.h"

void AChapter_01GameModeBase::BeginPlay()

This code currently doesn't do anything, but it gives us the ability to add changes to it later on in the future recipes of this chapter.

  1. Save both files and return to the Unreal editor. From the editor, click on the Compile button:

If all goes well, you should see a menu appear on the bottom-right of the screen, and after a period of time, you should see it say Compile Complete!:

It is also possible to compile your code in Visual Studio by right-clicking on the project from the Solution Explorer and selecting Build. Upon completion, when we go back to the Unreal editor, it should automatically load the changes that were made.

It is important for us to remember to compile our code any time we make changes to our code files. Otherwise, we will not be able to see those changes reflected in our project.

For more information on compiling your own code for Unreal Engine 4, check out https://docs.unrealengine.com/en-US/Programming/QuickStart.

UE4 – logging with UE_LOG

Logging is extremely important for outputting internal game data. Using log tools lets you print information into a handy little Output Log window in the UE4 editor.

Getting ready

When coding, we may sometimes want to send some debug information out to the UE log window. This is possible using the UE_LOG macro. A macro is a fragment of code that has been given a name. Whenever the name is used in code, it is replaced by the contents of the macro at compile time. Log messages are an extremely important and convenient way to keep track of information in your program as you are developing it.

You should have a code file to complete this recipe. If this is your first time coding in Unreal, you should complete the previous recipe before continuing with this one.

How to do it...

  1. In your code, enter a line of code using the following form:
UE_LOG(LogTemp, Warning, TEXT("Some warning message") );

For instance, if you wanted to add this to the script in the previous recipe, it may look like this:

#include "Chapter_01GameModeBase.h"

void AChapter_01GameModeBase::BeginPlay()

// Basic UE_LOG message
UE_LOG(LogTemp, Warning, TEXT("Some warning message") );
  1. Turn on the Output Log inside the UE4 editor by going to Window | Developer Tools | Output Log to see your log messages printed in that window as your program is running:
  1. If you play your game by clicking on the Play button from the top toolbar, you should notice our text being displayed in yellow on the log:
To make your output easier to see, you can clear the Output Log at any time by right-clicking on it within the window and selecting Clear Log.

How it works...

The UE_LOG macro accepts a minimum of three parameters:

  • The Log category (we used LogTemp here to denote a log message in a temporary log)
  • The Log level (we used a warning here to denote a log message, printed in yellow warning text)
  • A string for the actual text of the log message itself

Do not forget the TEXT() macro around your log message text, as it will convert the text into a format that is usable by UE_LOG. For those more familiar with coding, the TEXT() macro promotes the enclosed text to Unicode (it prepends an L) when the compiler is set to run with Unicode on.

UE_LOG also accepts a variable number of arguments, just like printf() from the C programming language:

#include "Chapter_01GameModeBase.h"

void AChapter_01GameModeBase::BeginPlay()

// Basic UE_LOG message
UE_LOG(LogTemp, Warning, TEXT("Some warning message") );

// UE_LOG message with arguments
int intVar = 5;
float floatVar = 3.7f;
FString fstringVar = "an fstring variable";
UE_LOG(LogTemp, Warning, TEXT("Text, %d %f %s"), intVar, floatVar, *fstringVar );

There will be an asterisk * just before the FString variable when using UE_LOG to dereference the FString to a regular C-style TCHAR pointer. This means that it is converting the pointer into the actual value it is pointing at.

TCHAR is usually defined as a variable type where, if Unicode is being used in the compile, the TCHAR resolves to the built-in data type, wchar_t . If Unicode is off (the _UNICODE compiler switch is not defined), then TCHAR resolves to simply the standard char type.
For more information on TCHAR and working with strings in general with C++, check out https://docs.microsoft.com/en-us/windows/desktop/learnwin32/working-with-strings#tchars.

Don't forget to clear your log messages after you no longer need them from the source! Otherwise, your console may become bloated with messages and make it difficult to find things you are looking for.


UE4 – making an FString from FStrings and other variables

When coding in UE4, you often want to construct a string from variables. This is pretty easy using the FString::Printf or FString::Format function.

Getting ready

For this, you should have an existing project into which you can enter some UE4 C++ code. Putting variables into a string is possible via printing. It may be counter intuitive to print into a string, but you can't just concatenate variables together and hope that they will automatically convert into strings, as in some languages, such as JavaScript.

How to do it...

In this recipe, we will see how to print in two different ways. First, we will be using FString::Printf():

  1. Consider the variables you'd like to be printed into your string. Note what each variable type is.
  2. Open and take a look at a reference page of the printf format specifiers, such as http://en.cppreference.com/w/cpp/io/c/fprintf. For each variable you want to print, node what the specifier is. For example, %s for a formatted string.
  3. Try code such as the following:
FString name = "Tim"; 
int32 mana = 450; 
FString string = FString::Printf( TEXT( "Name = %s Mana = 
%d" ), *name, mana );

Notice how the preceding code block uses the format specifiers precisely like the traditional printf function does. In the preceding example, we used %s to place a string in the formatted string, and %d to place an integer in the formatted string. Different format specifiers exist for different types of variables, and you should look them up on a site such as cppreference.com.

It is also possible to print a string using FString::Format().

  1. Write code in the following form:
FString name = "Tim"; 
int32 mana = 450; 
TArray< FStringFormatArg > args; 
args.Add( FStringFormatArg( name ) ); 
args.Add( FStringFormatArg( mana ) ); 
FString string = FString::Format( TEXT( "Name = {0} Mana =
{1}" ), args );

UE_LOG( LogTemp, Warning, TEXT( "Your string: %s" ),
*string );

With FString::Format(), instead of using correct format specifiers, we use simple integers and a TArray of FStringFormatArg instead. FstringFormatArg helps FString::Format() deduce the type of variable to put in the string. Refer to the following screenshot:

No matter which method you use, upon calling UE_LOG and you will get the same output.

About the Authors

  • John P. Doran

    John P. Doran is a passionate and seasoned technical game designer, software engineer, and author who is currently based in Songdo, South Korea. His passion for game development began at an early age.

    For over a decade, John has gained extensive hands-on expertise in game development, working in various roles ranging from game designer to lead UI programmer in teams consisting of just himself to over 70 people in student, mod, and professional game projects, including working at LucasArts on Star Wars: 1313. Additionally, John has worked in game development education teaching in Singapore, South Korea, and the United States at schools including the DigiPen Institute of Technology and Bradley University. To date, he has authored over 10 books on game development.

    John is currently an instructor at George Mason University Korea. Prior to his present ventures, he was an award-winning videographer.

    Browse publications by this author
  • William Sherif

    William Sherif is a C++ programmer with more than eight years' experience in the programming world, ranging from game programming to web programming. He also worked as a university course instructor (sessional) for seven years. Additionally, he released several apps on the iTunes store, including Strum and MARSHALL OF THE ELITE SQUADRON. In the past, he has won acclaim for delivering course material in an easy-to-understand manner.

    Browse publications by this author
  • Stephen Whittle

    Stephen Whittle is a game developer and educator with nearly 10 years' development experience, most of which has been done using the Unreal Engine. He is a community contributor to the engine, having features or bug fixes included in almost every major version of the engine since its public release.

    Browse publications by this author

Latest Reviews

(2 reviews total)
Honestly, I don't know why people are hating on this book here and on Amazon. Unreal Engine is woefully under-documented, and this book steps in to be the missing manual that explains memory management and slate UI and countless other things, with lots of code samples. As an experienced developer moving from Unity to Unreal, this book has been essential in getting my head around the Unreal API.
had coding mistakes Some can be fixed and some not .This guy is really not born to do this

Recommended For You

Unreal Engine 4.x Scripting with C++ Cookbook - Second Edition
Unlock this book and the full library for FREE
Start free trial