Reader small image

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

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

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

Right arrow

Learning C++ and Object-Oriented Programming

To use C++ to program games in Unreal Engine, you need to learn the C++ programming language. Almost all game engines need to support at least one scripting programing language because scripting provides interfaces that developers can use to control the game flow, integrate complex game logic, manipulate interactions between players and game entities, as well as process game events.

In order to utilize the Unreal Engine C++ APIs, it is essential to have a solid understanding of Object-Oriented Programming (OOP) principles and possess basic skills in C++ programming, which is what we will focus on in this chapter.

In this chapter, we will cover the following topics:

  • What is C++?
  • Exploring the C++ program structure
  • Defining C++ functions
  • Working with a basic calculator program
  • Learning the C++ syntax
  • Working on the improved calculator program
  • Creating references and pointers
  • Understanding OOP
  • Working...

Technical requirements

The code for this chapter can be found at https://github.com/PacktPublishing/Unreal-Engine-5-Game-Development-with-C-Scripting/tree/main/Chapter03.

What is C++?

C++ is a programming language that supports OOP, can be used to create high-performance applications, and gives developers low-level control over system resources and memory. C++ is the most suitable programming language for certain applications that have special demands on performance and low-level system controls (for example, operating systems, embedded systems, game applications, and graphics rendering).

C++ is designed to be a compiled language, which means it is generally translated into machine language code that can be directly understood and executed by a system, making the generated code highly efficient:

Figure 3.1 – Compiling C++ source code and executing machine language code

Figure 3.1 – Compiling C++ source code and executing machine language code

While writing C++ scripts in Unreal Engine, whenever you make changes, you need to compile your code first and then launch your game. Since Visual Studio comes with the C++ compiler, you should have no problem building your code in the IDE.

C...

Exploring the C++ program structure

In C++, programs execute code line by line, with each statement typically terminated by a semicolon. A collection of code lines that perform specific tasks can be grouped as a function, enclosed by a pair of curly braces, with the function having a name followed by a set of parentheses.

For example, the main.cpp file we created in Chapter 2 has two statement lines of code – the two lines of code are enclosed within a pair of curly braces, and the grouped block of code’s function name is main (see Figure 3.2).

Figure 3.2 – The main.cpp code sample

Figure 3.2 – The main.cpp code sample

C++ source programs generally follow the same program structure:

  • #include statements at the beginning of the program, which allow this program to access the C++ system library and other C++ source program functionalities. #include statements are special statements that don’t end with a semicolon.

Note

The C++ system library is...

Defining C++ functions

A function is a block of code that only runs when it is called. Functions are usually defined and used to perform certain actions, and they can be called anytime when needed; therefore, they are reusable code. Through the use of functions, we can avoid redundant code, reducing the risk of code inconsistency and the chance of program bugs.

Defining functions with or without parameters

To define a function, you should specify the name and return type of the function, followed by a pair of parentheses. Presented here is a function that has no parameter and a void return type:

void DisplayLabel(){
  std::cout  << "The result of 1 + 2 is ";
}

You can pass data as parameters into a function, and the function parameters are placed in between the parentheses. Presented here is a function that has two int parameters and returns the addition of the two input values as the result:

int Add(int a, int b){
  return...

Working with a basic calculator program

The MYCPP_02 program should have a main() function and an Add() function. The signature and the tasks defined for these two functions are as follows:

  • void Main(): This calls the Add() function to calculate 1 + 2 and 3 + 4 and output the results
  • int Add(int a, int b): This adds up the two integer parameter values, a and b, and returns the calculation result

So, let’s create a new C++ project, name it MyCPP_02, and then add a new main.cpp file.

Then, type in the following code for main.cpp:

#include <iostream>int Add(int a, int b)
{
  return a + b;
}
void main()
{
  std::cout << "My Calculations" << std::endl;
  int result = Add(1, 2);
  std::cout << "Integer addition: 1 + 2 = "
                << result
       ...

Learning the C++ syntax

Learning C++ syntax is crucial to write correct and reliable code, and the ability to write effective C++ code is a fundamental skill that C++ developers must possess. In this section, we will introduce the essentials of C++ syntax, beginning with data types.

Using the C++ data types

Besides the int data type that we just have used, C++ has many other built-in data types that can be used. Here is a list of some basic data types:

Working on the improved calculator program

In this new program, we want to add the following features:

  • Allow a user to repeatedly input numbers for calculations
  • Make another version of the Add function, which adds float values
  • Add some comments to explain what the code blocks do
  • Put the Add functions into the separate header and source files – Calculator.h and Calculator.cpp

Follow these steps:

  1. Create a new project and name it MyCPP_03.
  2. Add the main.cpp, calculator.cpp, and calculator.h files to the project. Your Solution Explorer window should now have the files under the Header Files and Source Files folders, like so:
Figure 3.16 – The MyCPP_03 Solution Explorer

Figure 3.16 – The MyCPP_03 Solution Explorer

  1. Next, type the following code into the main.cpp file:
    #include <iostream>
    #include "Calculator.h"
    using namespace std;
    void main()
    {
        cout << "My Calculations" << endl;
     &...

Creating references and pointers

When writing C++ code, a variable may not be accessed in only one place. Copying variable values into multiple places brings the risk of inconsistent variable values, as well as lower performance and more memory usage.

Look at the following addition example:

float Add(float a, float b){
  return a + b;
}
Void main()
{
  int x = 1, y = 2;
  cout << Add(x, y);
}

You can see that the function’s parameters actually copy the x and y values into the two a and b variables, which means that a and b have their own storage, and any value changes on a and b within the Add function won’t affect the values of x and y.

Using references and pointers in C++ can not only help to use less memory and improve performance but also provide the flexibility to modify the original variable values.

References

A reference variable is a reference to an existing variable, and it is defined with the & operator...

Understanding OOP

Before diving into the world of OOP, it is necessary to lay the groundwork by explaining some fundamental OOP concepts and terms. Following this, you will learn how to create C++ classes and utilize the new classes to instantiate objects, allowing for the practical implementation of OOP principles.

What is OOP?

In the MyCPP_0x projects, we wrote functions to perform operations on the data. The approach we used is actually called procedural programming.

OOP is defined as a programming paradigm built on the concept of objects. OPP tries to reflect real-world concepts by creating objects that contain attributes (fields) and functions (methods).

There are three major pillars on which OOP relies:

  • Encapsulation: This means that data and functions can be wrapped up into classes so that some sensitive data is hidden from users.
  • Inheritance: This means that a class can derive from another base class to be its child class. The child class can inherit...

Working on an OOP calculator program

Let’s create a new project, MyCPP_04, and create the main.cpp, Calculator.cpp, and Calculator.h files. What we mainly want to do is to create a Calculator class and then make the Add functions the class methods.

Follow these steps:

  1. Type the following code into the main.cpp file:
    #include <iostream>
    #include "Calculator.h"
    using namespace std;
    void main()
    {
        Calculator calculator;  //defines the calculator object
        cout << "My Calculations: " << calculator.GetName() << endl;
        float input1, input2;
        while (true)
        {
            cout << "Input the first value (0 to exit): ";
            cin >> input1;
            if (input1 == 0)  //exit if the...

Summary

In this chapter, you learned the essentials of the C++ programing language. This chapter covered the topics of the compilation process, the program structure, data types, variable creation, functions, comments, the Standard Library’s user input, reference and pointer creations, flow control, and OOP.

The three exercises should be very helpful to learn and practice the C++ syntax, procedural programming, and OOP skills. The five MyCPP_x projects are also good samples that can be referenced in your later studies.

Since C++ is a very powerful programming language, providing ample features and functionalities, it is not possible to cover everything in this chapter. We will explain other C++ syntaxes when they are used.

You should now have the necessary knowledge about C++ programming. In the next chapter, we will investigate the Unreal Engine-generated C++ source code for the shooter game. This should help you to quickly understand the commonly used Unreal Engine...

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

Author (1)

author image
ZHENYU GEORGE LI

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

Data type

Size (bytes)

Description

int

4

Stores signed integer numbers without decimals.

Data range: -2,147,483,648 to 2,147,483,647

Example: int i = -1; int j = 1;

unsigned int

4

Stores unsigned integer numbers without decimals.

Data range: 0 to 4,294,967,295

...