Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Unreal Engine 4.x Scripting with C++ Cookbook
Unreal Engine 4.x Scripting with C++ Cookbook

Unreal Engine 4.x Scripting with C++ Cookbook: Develop quality game components and solve scripting problems with the power of C++ and UE4 , Second Edition

Arrow left icon
Profile Icon John P. Doran Profile Icon Sherif Profile Icon Whittle
Arrow right icon
$20.98 $29.99
Full star icon Full star icon Full star icon Full star icon Half star icon 4.1 (10 Ratings)
eBook Mar 2019 708 pages 2nd Edition
eBook
$20.98 $29.99
Paperback
$43.99
Subscription
Free Trial
Renews at $19.99p/m
Arrow left icon
Profile Icon John P. Doran Profile Icon Sherif Profile Icon Whittle
Arrow right icon
$20.98 $29.99
Full star icon Full star icon Full star icon Full star icon Half star icon 4.1 (10 Ratings)
eBook Mar 2019 708 pages 2nd Edition
eBook
$20.98 $29.99
Paperback
$43.99
Subscription
Free Trial
Renews at $19.99p/m
eBook
$20.98 $29.99
Paperback
$43.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Unreal Engine 4.x Scripting with C++ Cookbook

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

Introduction

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"

/**
*
*/
UCLASS()
class CHAPTER_01_API AChapter_01GameModeBase : public AGameModeBase
{
GENERATED_BODY()
public:
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()
{
Super::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()
{
Super::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()
{
Super::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.

Left arrow icon Right arrow icon

Key benefits

  • Build captivating multiplayer games using Unreal Engine and C++
  • Incorporate existing C++ libraries into your game to add extra functionality such as hardware integration
  • Practical solutions for memory management, error handling, inputs, and collision for your game codebase

Description

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!

Who is this book for?

If you are really passionate game developer looking for solutions to common scripting problems, then this is the book for you. Understanding of the fundamentals of game design and C++ is expected to get the most from this book.

What you will learn

  • Create C++ classes and structs that integrate well with UE4 and the Blueprints editor
  • Discover how to work with various APIs that Unreal Engine already contains
  • Utilize advanced concepts such as events, delegates, and interfaces in your UE4 projects
  • Build user interfaces using Canvas and UMG through C++
  • Extend the Unreal Editor by creating custom windows and editors
  • Implement AI tasks and services using C++, Blackboard, and Behavior Trees
  • Write C++ code with networking in mind and replicate properties and functions

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Mar 29, 2019
Length: 708 pages
Edition : 2nd
Language : English
ISBN-13 : 9781789803372
Languages :
Concepts :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Mar 29, 2019
Length: 708 pages
Edition : 2nd
Language : English
ISBN-13 : 9781789803372
Languages :
Concepts :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 131.97
Hands-On Artificial Intelligence with Unreal Engine
$43.99
Unreal Engine 4 Virtual Reality Projects
$43.99
Unreal Engine 4.x Scripting with C++ Cookbook
$43.99
Total $ 131.97 Stars icon
Banner background image

Table of Contents

15 Chapters
UE4 Development Tools Chevron down icon Chevron up icon
Creating Classes Chevron down icon Chevron up icon
Memory Management, Smart Pointers, and Debugging Chevron down icon Chevron up icon
Actors and Components Chevron down icon Chevron up icon
Handling Events and Delegates Chevron down icon Chevron up icon
Input and Collision Chevron down icon Chevron up icon
Communication Between Classes and Interfaces: Part I Chevron down icon Chevron up icon
Communication Between Classes and Interfaces: Part II Chevron down icon Chevron up icon
Integrating C++ and the Unreal Editor: Part I Chevron down icon Chevron up icon
Integrating C++ and the Unreal Editor: Part II Chevron down icon Chevron up icon
Working with UE4 APIs Chevron down icon Chevron up icon
Multiplayer Networking in UE4 Chevron down icon Chevron up icon
AI for Controlling NPCs Chevron down icon Chevron up icon
User Interfaces - UI and UMG Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.1
(10 Ratings)
5 star 40%
4 star 50%
3 star 0%
2 star 0%
1 star 10%
Filter icon Filter
Top Reviews

Filter reviews by




Jamell Jul 18, 2019
Full star icon Full star icon Full star icon Full star icon Full star icon 5
It touches on enough of everything to go from no knowledge to programmer. Very easy to follw and understand. Well done.
Amazon Verified review Amazon
Amazon Customer Jan 21, 2022
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I normally don't review amazon books, but I'm making an exception for this one. John P Doran has become by far my favourite resource for looking up code examples on features that need to be developed in my game. I was a bit put off by this book initially based off the reviews it got, but I assure you the information he talks about in this book are as relevant today as they were 3 years ago. there are some functions he uses that are deprecated. but if you search the function name it will be easy to find updated function call. The way the authors structure the book is they first give you the source code then explain each function call and why it's being used in this way. Most of the time I have to read the unreal engine source code to get the features I need implemented in C++ and I promise you this book is an excellent complement to that way of learning/working. From experience a lot of ue4 books who don't want to get tangled in advance ue4 features will choose to exclude the topic all together. That is not the case with this book. I have been searching for weeks on a code resource to understand slate programming " Styling, associated delegates, loading custom assets" and this was the only book that actually put in a good amount of effort explaining those topics. this book will give you a proper direction of what part of the UE4 source code actually matter to you and how the source code can be used to create your custom features.
Amazon Verified review Amazon
deusprogrammer Aug 09, 2019
Full star icon Full star icon Full star icon Full star icon Full star icon 5
What this book is: a collection of code snippets explaining how to do several useful/vital operations using C++ in UE4.What this book isn't: a tutorial.This book gave me exactly what I needed. I learned enough about UE4 to be dangerous with it, and I already knew C++. I wanted to learn how to put those two concepts together so I could use UE4 the way a programmer wants to use it. Excellent book.
Amazon Verified review Amazon
Kindle Customer Jan 25, 2021
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Best book for starting with Unreal cpp programming! you need to have basic knowledge about c++ for this book.
Amazon Verified review Amazon
Mattias Persson Mar 08, 2020
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
This is a good programming guide to the various C++ features of the Unreal Engine 4.x.In order to make good use of this book you need some knowledge of C++, or at least programming in general, and of the engine. People who have given this book a very low score probably lacked one or both.I know programming but come from C#. I have a moderate knowledge of the engine. I found this book one of several useful tools to get into C++ for Unreal Engine.People mention YouTube tutorials. Problem with them is that you have no control of the skill of the tutor.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.