Unreal Engine 5 Game Development with C++ Scripting - ZHENYU GEORGE LI - E-Book

Unreal Engine 5 Game Development with C++ Scripting E-Book

Zhenyu George Li

0,0
29,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Unreal Engine is one of the most popular and accessible game engines in the industry, creating multiple job opportunities. Owing to C++ scripting's high performance, advanced algorithms, and engineering maintenance, it has become the industry standard for developing commercial games. However, C++ scripting can be overwhelming for anyone without a programming background. Unreal Engine 5 Game Development with C++ Scripting will help you master C++ and get a head start on your game development journey.
You’ll start by creating an Unreal Engine C++ project from the shooter template and then move on to building the C++ project and the C++ code inside the Visual Studio editor. You’ll be introduced to the fundamental C++ syntax and essential object-oriented programming concepts. For a holistic understanding of game development, you’ll also uncover various aspects of the game, including character creation, player input and character control, gameplay, collision detection, UI, networking, and packaging a completed multiplayer game.
By the end of this book, you’ll be well-equipped to create professional, high-quality games using Unreal Engine 5 with C++, and will have built a solid foundation for more advanced C++ programming and game development technologies.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB

Seitenzahl: 335

Veröffentlichungsjahr: 2023

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Unreal Engine 5 Game Development with C++ Scripting

Become a professional game developer and create fully functional, high-quality games

Zhenyu George Li

BIRMINGHAM—MUMBAI

Unreal Engine 5 Game Development with C++ Scripting

Copyright © 2023 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Group Product Manager: Rohit Rajkumar

Publishing Product Manager: Vaideeshwari Muralikrishnan

Senior Editor: Hayden Edwards

Technical Editor: Simran Udasi

Copy Editor: Safis Editing

Project Coordinator: Aishwarya Mohan

Proofreader: Safis Editing

Indexer: Manju Arasan

Production Designer: Ponraj Dhandapani

Marketing Coordinators: Namita Velgekar & Nivedita Pandey

First published: August 2023

Production reference: 1110823

Published by Packt Publishing Ltd.

Grosvenor House

11 St Paul’s Square

Birmingham

B3 1R

ISBN 978-1-80461-393-1

www.packtpub.com

Foreword

I have known and worked with George Li in various capacities for more than 20 years.

We met first as colleagues at a private college of interactive arts in downtown Vancouver, Canada. I was a full professor of linguistics at a university in the area, with extensive experience in developing a cognitive science program at the university. Establishing a curriculum for such a program involved familiarizing myself with areas well beyond the area of my specific academic position and collaborating closely with colleagues – particularly in computing science (cognitive), psychology, and philosophy (particularly concerning socio-epistemological issues such as AI). It was in this spirit that I was happy to associate myself with a private college, focusing on language study and teaching, together with preparing students to handle 3D computer applications (e.g., 3ds Max, 3D GameStudio, and Unreal) and showing them how to generate animation materials for film, TV, and games.

George Li was in charge of all the technical requirements of the college. I very quickly realized that he was not merely extremely competent and forthcoming (he had already occupied high-level computing-related positions, software engineering for instance, in China prior to emigrating to Canada) but also computationally competent and brilliantly innovative. He also had a particular interest in the development of game engines and was already collaborating with his colleague, Charles Yeh, on a practical reference book, XNA PC & Xbox360 C# Game Programming, with proprietary-produced text and games to his credit.

As colleagues in the college, George and I found common, mutually strengthening interests. Eventually, he and I found ourselves in charge of creating a two-year interactive-arts program curriculum for the college.

My whole career, at universities in the UK and Canada, and as a member of the editorial boards of a major academic journal and a very influential series, has closely involved the evaluation of the intellectual quality of people’s capabilities and work, and in my opinion, George Li’s innate talents shine out clearly throughout his work and will continue to do so in the future. His ability to express his knowledge of the subject at hand is outstandingly demonstrated in all his work, performance, expressions, and character.

This book, like the one co-authored with Yeh, is designed for independent developers and company training, plus for reference after post-secondary education. The knowledge presented herein is most intelligently, clearly, and effectively presented so as to be as efficiently applicable and pedagogically effective as possible on any device or platform, producing high-quality games, accessories, and edits.

This volume will certainly stand the test of time and fulfill the majority of the needs of those working in the field of gaming. However, I am certain that George will make further, very crucial contributions to this topic.

Until then, this volume will serve you excellently, helping you enjoy and prosper with your future activities and products.

Dr. E. Wyn Roberts (M.A. Ph.D (Cantab.))

Emeritus Professor of Linguistics, Simon Fraser University

Contributors

About the author

Zhenyu George Li is a passionate video game developer with over 20 years of experience in the field. As a seasoned software engineer, George has contributed significantly to the development of numerous games throughout his career and currently serves as a senior development consultant at Unity.

George’s fascination with video games was sparked during his college studies, igniting a passion that would shape his professional journey. During the early stages of his game development endeavors, George immersed himself in technologies such as Visual Basic, C/C++, DirectX, OpenGL, and Windows GUI. These foundational experiences laid the groundwork for his subsequent success in the industry.

Throughout his career, George has made substantial contributions to various commercial games. Notable titles in his portfolio include Halo Infinite, Magic: The Gathering Arena, Stela, Dead Rising 2, The Bigs 2, and so on. His involvement in these projects has allowed him to gain extensive knowledge and practical experience in a wide range of domains, including programming, game engines, gameplay and AI, graphics, animation, multiplayer games, multiplayform games, and game physics. In practical applications, George has used both the Unreal and Unity engines in the development of real game projects.

In addition to his achievements as a game developer, George has also honed his teaching abilities during his eight years of college-level instruction. He has shared his knowledge and expertise with aspiring developers, serving as a lecturer at the Vancouver Film School (VFS), the College of Interactive Arts, and Hefei Union University. During his teaching at VFS, George instructed students in the intricacies of Unreal Engine.

I express my gratitude to my wife, Alison Guo, for her support in handling family responsibilities and for enabling me to dedicate time to completing this book. I also extend my thanks to Sarah Beck and Willy Campos for their encouragement and support throughout the writing process.

About the reviewers

Aditya Dutta holds a game programming advanced diploma from Humber College and is a highly accomplished senior software engineer at Archiact Interactive, bringing expertise in Unreal Engine and C++ system design and implementation.

With a strong collaborative spirit, Aditya leads feature development and takes ownership of tools while actively improving team processes. These leadership skills were evident during his tenure as lead programmer at Humber College, where he successfully guided and mentored a team of programmers, overseeing the technical aspects of significant projects in the virtual production and architecture industries.

His contributions at UP360 Inc. as a programmer included shipping numerous training VR simulations, developing iterative tools, and implementing gameplay mechanics using Unreal Engine.

Michael Oakes is a senior software consultant for Unity and has over 27 years of experience in the IT industry. He has worked with real-time 3D and games for over eight years, specializing in mixed reality design and development, shader programming, and AI and multiplayer systems.

He has worked as a technical consultant on other titles, including Packt Publishing’s Learn ML-Agents – Fundamentals of Unity Machine Learning, written by Micheal Lanham.

Table of Contents

Preface

Part 1 – Getting Started with Unreal C++ Scripting

1

Creating Your First Unreal C++ Game

Technical requirements

Understanding C++ scripting in Unreal

What is the difference between C++ and Blueprint?

When do you use C++?

What is the difference between C++ programming and C++ scripting?

Creating your C++ Shooter project from a template

Installing Visual Studio 2022

Ensuring your UE has the source code installed

Launching the UE5 editor through the Epic Games Launcher

Creating the MyShooter C++ project

Associating VS with UE5 as the default source code editor

Opening the C++ source code in VS (optional)

Converting an existing Blueprint project to a C++ project

Summary

2

Editing C++ Code in Visual Studio

Technical requirements

Launching VS

Walking through the VS IDE’s UI

Code editor

Menus

Search box

Toolbar

Solution Explorer

Output window

Error List window

Editing code in VS

Controlling the caret (input cursor)

The text editing keys

Code selection

IntelliSense

Useful editing hotkeys

Practicing C++ coding

Creating a new C++ solution in VS

Creating the main.cpp file

Changing the editor theme

Writing the initial code for main.cpp

Adding the Calculator class

Summary

3

Learning C++ and Object-Oriented Programming

Technical requirements

What is C++?

Exploring the C++ program structure

Defining C++ functions

Defining functions with or without parameters

Calling functions

Writing the main() function

Working with a basic calculator program

Learning the C++ syntax

Using the C++ data types

Defining variables

Using C++ arrays

Using C++ operators

Accepting user input

Adding C++ comments

Controlling the C++ flow

Working on the improved calculator program

Creating references and pointers

References

Pointers

Understanding OOP

What is OOP?

What are classes and objects?

Creating classes in C++

Creating objects in C++

Working on an OOP calculator program

Adding constructor and getter functions for the calculator class

Creating the CalculatorEx class, which inherits from the Calculator class

Summary

4

Investigating the Shooter Game’s Generated Project and C++ Code

Technical requirements

Understanding the MyShooter C++ project structure

Understanding the game program structure

Getting familiar with the source code

MyShooterCharacter.h

MyShooterCharacter.cpp

MyShooterProjectile.h and MyShooterProjectile.cpp

TP_PickUpComponent.h and TP_PickUpComponent.cpp

TP_WeaponComponent.h and TP_WeaponComponent.cpp

MyShooter.h and MyShooter.cpp

MyShooterGameMode.h and MyShooterGameMode.cpp

MyShooter.Build.cs, MyShooter.Target.cs, and MyShooterEditor.target.cs

Launching Unreal Editor and opening the game project in Visual Studio

Summary

Part 2 – C++ Scripting for Unreal Engine

5

Learning How to Use UE Gameplay Framework Base Classes

Technical requirements

Creating a Pangaea top-down game project

Understanding the gameplay framework base classes

Creating game actor classes

Creating the ADefenseTower class

Creating the AProjectile class

Creating the APlayerAvatar class

Recompiling C++ projects

Using the UPROPERTY macro

The UPROPERTY syntax

The UPROPERTY specifiers and metadata keys

Marking the ADefenseTower, AProjectile, and APlayerAvatar attributes as UE properties

Using the UFUNCTION macro

The UFUNCTION syntax

UFUNCTION specifiers and metadata keys

Tagging ADefenseTower and APlayerAvatar member functions as UFUNCTION macros

Adding components to the new actors

Including component header files

Defining private properties for these two components

Adding public getter functions to the components

Creating components in the class constructor

Creating blueprints from the new actor classes

Learning about the Unreal gameplay framework classes

Locating and creating gameplay framework classes in Pangaea

Learning about the PlayerController class

Learning about the GameModeBase class

GameState

GameInstance

Retrieving class instances from your code

Using the Cast template function

Summary

6

Creating Game Actors

Technical requirements

Setting up the player avatar

Adding SpringArmComponent and CameraComponent to PlayerAvatar

Initializing the player avatar

Setting up the character’s SkeletalMeshComponent

Importing the character model

Using the Hero skeletal mesh in BP_PlayerAvatar

Replacing the game’s player pawn

Creating the player avatar’s animation blueprint

Creating the PlayerAvatarAnimInstance class

Creating the ABP_PlayerAvatar blueprint

Creating the State Machine on ABP_PlayerAvatar

Syncing the movement speed with the animation instance

Summary

7

Controlling Characters

Technical requirements

Controlling the player character to attack

Adding the Attack action to the action map

Binding the handler function to the Attack action

Implementing the OnAttackPressed() action handler function

Implementing the CanAttack() and Attack() functions

Processing non-loop animations

Implementing the OnStateAnimationEnds function

Destroying actors

Creating the enemy character

Creating the Enemy class

Creating the EnemyController class

Creating the ABP_Enemy animation blueprint

Creating the BP_Enemy blueprint

Testing the game

Summary

8

Handling Collisions

Technical requirements

Understanding collision detection

Setting the collision presets

Using collisions for game interactions

Downloading and creating the weapon, defense tower, and fireball actors

Picking up weapons

Spawning a weapon for the enemy

Defense tower firing fireballs

Moving the fireball and checking whether the target is hit

Processing a defense tower hit

Summary

9

Improving C++ Code Quality

Technical requirements

Refactoring code

Combining the PlayerAvatarAnimInstance and EnemyAnimInstance classes

Making PangaeaCharacter the parent class of APlayerAvatar and AEnemy

Refining code

Using caching variables

Creating a fireball pool

Outputting debug messages

Using the UE_LOG macro

Printing debug messages to the screen

Checking an Actor instance’s actual class type

Summary

Part 3 – Making a Complete Multiplayer Game

10

Making Pangaea a Network Multiplayer Game

Technical requirements

Comparing single-player and multiplayer games

Launching the multiplayer Pangaea game in the editor

Understanding multiplayer game network modes

Handling network synchronizations

Notifying player attacks with RPCs

Syncing actor variables to clients with replications

Updating the character health bar with RepNotify

Processing hits on the server

Spawning fireballs on the server side

Summary

11

Controlling the Game Flow

Technical requirements

Designing the Pangaea game’s flow

Creating the UI widgets

Creating BP_LobbyWidget

Creating BP_HUDWidget

Creating BP_GameOverWidget

Adding networking functions to PangaeaGameInstance

Adding UI widgets to game levels

Adding the game timer

Adding the Timer variable to the APangaeaGameState class

Making the Timer variable replicable

Defining OnTimeChangedDelegate

Creating and binding the custom event to OnTimeChangedDelegate

Counting down the timer

Designating APangaeaGameState as the project’s game state class

Destroying a base defense tower to win the game

Summary

12

Polishing and Packaging the Game

Technical requirements

Polishing the game

Importing and using high-quality game assets

Fixing bugs

Profiling and optimization

Using Unreal Engine console commands

Exploring modes and console commands

Executing console commands in C++

Packaging the game

Configuring the project settings for packaging

Making the build a windowed game

Avoiding the hardcoded path for finding content

Packaging the project

What to do next

Summary

Index

Other Books You May Enjoy

Part 1 – Getting Started with Unreal C++ Scripting

In this part, the primary focus will be on providing an introduction to the basics of C++ programming, specifically for game development with Unreal Engine. You will gain knowledge on creating a C++ game project in Unreal, as well as utilizing MS Visual Studio to access and modify the game’s source code. Moreover, essential concepts of C++ and object-oriented programming, along with their syntax, will be introduced. Building upon this foundation, we will examine the generated source code to conduct an initial investigation into the game project.

This part contains the following chapters:

Chapter 1, Creating Your First Unreal C++ GameChapter 2, Editing C++ Code in Visual StudioChapter 3, Learning C++ and Object-Oriented ProgrammingChapter 4, Investigating the Shooter Game’s Generated Project and C++ Code

1

Creating Your First Unreal C++ Game

Unreal Engine (UE) is one of the most popular 3D computer graphics game engines developed by Epic Games, providing a comprehensive set of tools and functionalities to develop high-quality, immersive 3D simulations. The engine offers its intuitive visual scripting system, Blueprint, and a robust C++ programming framework for developers of all skill levels. This book provides a concise introduction to C++ programming and demonstrates how to write C++ scripts in UE for game development.

In this chapter, you will learn the essential skill of creating an Unreal C++ project from scratch or converting an existing Unreal Blueprint project into an Unreal C++ project, which serves as a fundamental skill to advance in game development. By mastering this process, you will gain the necessary foundation to take your game development abilities to the next level.

This chapter will cover the following topics:

Understanding C++ scripting in UnrealCreating your C++ shooter project from a templateConverting an existing Blueprint project to a C++ project

Technical requirements

As a reader of this book, you will be expected to have common computer operational skills. You should also have basic knowledge of and experience with the UE5 editor, as well as some Blueprint scripting skills.

To follow this chapter, you should have installed Epic Games Hub and the 5.03 or later version of the engine editor on your computer. If you haven’t done so, please go to the official Epic website (https://www.unrealengine.com/en-US) to register an account and download the Epic Games Launcher.

The minimum required development environment is as follows:

Operating system: Windows 10Processor: Intel 7th generation or equivalentMemory: 16 GB of RAMGPU: GTX 1080 (or AMD equivalent)DirectX: Version 12Storage: 25 GB of available spaceAdditional notes: 8 GB of VRAM recommended

The official system requirements can be found here: https://docs.unrealengine.com/5.0/en-US/hardware-and-software-specifications-for-unreal-engine/. To save game editing time in the UE5 editor, it is recommended to use a computer with an i9 (or an AMD equivalent) CPU, 64 GB of RAM, and a GeForce RTX 3060 video card.

Understanding C++ scripting in Unreal

Before getting started, we need to answer some questions that people usually ask about C++ scripting. This will help to clarify the pros and cons of using C++, the reasons to use C++, and the difference between UE C++ scripting and C++ programming.

What is the difference between C++ and Blueprint?

Both C++ and Blueprint are scripting languages that can accomplish the same tasks, but one might be better suited than the other under certain circumstances. The main difference between them is that C++ is a programming language that allows you to write general-purpose, text-based code, whereas Blueprint is a visual scripting system for UE.

For UE projects, game studios usually use both C++ and Blueprint to develop commercial-level games. C++ is usually used for advanced techniques, complex algorithms, and big-scale logic code. If you can script with C++, you will have more chances to work on a professional team.

One of the most important advantages of using C++ is performance. C++ allows you to write low-level operational code. It also provides control over the core system that is not accessible to Blueprint. In addition, the final C++ code will eventually be optimized and compiled to be machine-friendly binary native code. On the other hand, Blueprint scripts are interpreted and executed by a middle layer, which means more execution time.

C++ code and files can be well-organized based on an entire project’s mechanics. It is easy to globally search, locate, and access code blocks to edit, maintain, and troubleshoot. In the meantime, it is also easier to read and understand a big chunk of code that implements complex algorithms and logic. Blueprint, on the other hand, is a context-sensitive scripting environment. Blueprint graphs are relatively independent. When a graph needs to solve complex logic, the nodes and the connection lines create messy spaghetti that can hardly be understood and maintained.

C++ also has some shortcomings. One example is that it may cause critical errors that may crash an entire system. That is usually caused by the developer’s mistakes. Since Blueprint is a protected layer, it is safer, and hence, the chances of the system crashing are fewer.

In conclusion, the choice between C++ and Blueprint should be made based on specific development requirements and conditions, considering the pros and cons of each approach.

When do you use C++?

Both C++ and Blueprint can handle game development processes without a problem. There is no exact rule that regulates when to use C++ or Blueprint. It mainly depends on your experience and the actual needs of different games. You make your own decision based on how much you know about the two scripting systems.

Before you start working on something, you can ask yourself this question: “Where does it make sense to use C++, and where does it make sense to use Blueprints?” We recommend basing your answer on the following aspects and trade-offs:

PerformanceLogic and algorithm complexityAccessibility to a system’s core functionsThe developer’s experience

If you want higher performance and deal with advanced game logic and system processes, and you are capable of coding and solving complex problems, you should go for C++.

What is the difference between C++ programming and C++ scripting?

You may be confused about the difference between C++ programming and C++ scripting. We want to clarify the meanings of these two terms.

C++ programming means using the C++ programming language to write code for any purpose; it doesn’t have to be just for UE projects. C++ scripting, in this book, is a specific dialect of the C++ programming language supported by the UE. It takes advantage of the power of C++ syntax and also works with UE’s Application Programming Interfaces (APIs), which allow developers to create and extend the engine’s functionalities for their games and the development environment’s context, such as objects, graphics, audio, and network communication.

Now that we have a basic overview of C++ and have learned why and when to use C++ for Unreal game developments, let’s dive deeper into C++ scripting by creating a sample project.

Creating your C++ Shooter project from a template

Now, it’s the time to get your hands dirty working on a UE5 C++ project yourself. We will go through the steps to create a new C++ project from scratch based on the First Person template.

The First Person template is one of the default game templates that come with UE. When you want to create a new project, you can pick this template from the Unreal Project Browser window. Our new MyShooter game will derive all the features from the template game, and we don’t have to do any additional work.

To get started with C++ scripting, we first need to install an IDE. In this book, we will use MS Visual Studio 2022 as an example.

Installing Visual Studio 2022

Visual Studio (VS) is an Integrated Development Environment (IDE) from Microsoft. It is a tool used to create, edit, debug, and compile code. In order to do C++ scripting, you need to go to the official website at https://visualstudio.microsoft.com/vs/ and download the Community 2022 version installation package (see Figure 1.1).

Figure 1.1 – Downloading VS 2022

Note

To install VS, a Microsoft account is typically required. If you don’t have a Microsoft account, you can register using the following page: https://account.microsoft.com/account/.

Next, launch VisualStudioSetup.exe inside the folder where you downloaded the VS installer (the \Downloads folder, for example).

Enable the two Game development with C++ and Desktop development with C++ checkboxes – these two options tell the installer to install the C++ compiler and the professional game development support for UE (see Figure 1.2).

Figure 1.2 – Picking workloads for the VS installation

Also, keep an eye on the following options on the Installation details panel that belongs to the Desktop development with C++ group, and make sure the following are checked:

C++ profiling toolsC++ AddressSanitizerWindows 10 SDKIntelliCodeIDE support for Unreal Engine

Then, click the Install button to install the workloads and reboot the system, and then you will see a prompt from the dialog popup (see Figure 1.3):

Figure 1.3 – The VS Done installing dialog box

The next thing we need to do is to confirm that we have installed the engine source code together with the UE5 editor. The reason why we need this is that when we generate a new project, the engine source code can be integrated into the new project; under certain circumstances, we may need to modify or customize the engine for the game’s specific needs.

Ensuring your UE has the source code installed

Before launching the UE5 editor, we first need to check whether Engine Source is installed for the editor. By doing this check, we make sure that the UE5 source code is integrated with the C++ projects we are going to create.

The three steps to check or install the engine source code are as follows:

Click the downward arrow button and choose Options from the drop-down menu.Make sure that the Engine Source option is checked.Press the Apply button:

Figure 1.4 – The UE5 Options menu

UE is an ongoing development product, with bugs and defects that may need to be fixed by its users. Also, professional developers sometimes modify the engine source code to adapt to their specific needs. An example of this is when we face an issue with geometry instancing (or instanced rendering) working only in the game’s development build but not in the release build, which is subsequently resolved by our engineer modifying the engine’s source code.

Note

Geometry instancing is a rendering technique that renders multiple instances of a visual object in a single draw call and provides each instance with some unique attributes: https://en.wikipedia.org/wiki/Geometry_instancing.

We are now ready to start the UE editor through the Epic Games Launcher.

Launching the UE5 editor through the Epic Games Launcher

Launching the UE5 editor is pretty straightforward. You simply click the Launch button on the 5.03 engine card to start the editor (see Figure 1.5).

Figure 1.5 – Launching the UE5 editor from the Epic Games Launcher

The next thing we want to do is to create a new game project. Let’s name the new project MyShooter.

Creating the MyShooter C++ project

To create the project, follow these steps (and see Figure 1.6for reference):

In the Unreal Project Browser window, choose the GAMES tab on the left side.Select the First Person template.Select the C++ button.Choose the project location (for example, C:\UEProjects) and type MyShooter in the Project Name field.Click the Create button.

Figure 1.6 – Creating the MyShooter project

The created game project also includes the starter content, which is packaged with assets and resources that can be used to prototype the game.

The engine will do some initialization work and then open the editor when things are ready. If you look at the project tree panel’s MyShooter tab in the bottom-left corner of the editor window, you should see the C++ Classes node on the same layer as the Content node (see Figure 1.7).

Figure 1.7 – The MyShooter C++ project opened in the UE5 editor

Associating VS with UE5 as the default source code editor

Since we created the C++, project, all the C++ source code for the game was already generated. To open the source files directly in the UE5 editor, we want to associate VS as the engine editor’s default IDE.

On the UE5 Editor’s main menu, select Edit | Editor Preferences to open the preference window, then find the General | Source Code item on the left panel, and finally, pick Visual Studio 2022 from the Source Code Editor dropdown (see Figure 1.8).

Figure 1.8 – Making VS the default source code editor

You can now use VS to open the source code files.

Opening the C++ source code in VS (optional)

If you want to open and view the C++ source code in VS, you can find the source code file (for example, C++/MyShooter/MyShooterCharacter.cpp) in the project and simply double-click on it (see Figure 1.9).

Figure 1.9 – Opening MyShooterCharacter.cpp source code in VS

The system will automatically launch VS, and the VS editor will open the MyShooterCharacter.cpp file (see Figure 1.10).

Figure 1.10 – Viewing the MyShooterCharacter.cpp source code in VS

Back in the Unreal editor, click the Play () button to start the game. While playing the game on the battlefield, you can control your character, move them around, and pick up the gun in front of them (see Figure 1.11).

Figure 1.11 – Playing the MyShooter game

We have learned how to create a UE C++ project from scratch. However, what if we already have a Blueprint project and want to convert it to a C++ project? UE allows developers to do it by adding a new C++ class to the project. Let’s practice converting a MyBPShooterBlueprint project.

Converting an existing Blueprint project to a C++ project

UE provides a very straightforward way to convert an existing Blueprint project to a C++ project. All you need to do is add a C++ class to your project and then let UE take care of the conversion and add the needed project files:

First of all, you have to create a Blueprint project, MyBPShoopter, under C:\UEProjects (you can choose a different path to create the new project). Use the same steps introduced in the Creating the MyShooter C++ project section, but choose BLUEPRINT instead of C++ for the creation of the MyBPShooter project.

Figure 1.12 – Creating MyBPShooter in UE5

Secondly, open the new project in UE5. Pay attention to the project tree; it doesn’t have the C++ Classes node at this stage.

Figure 1.13 – Open MyBPShooter in UE5

Select Tools | New C++ Class from the editor’s main menu, and then, in the Add C++ Class window (see Figure 1.14), choose Character as the base class (a class that contains common attributes and methods that are shared by its derived classes) to create the MyShooterCharacter class.

Figure 1.14 – Adding a new C++ class from the Character class

Once you click the Next> button, it will navigate to the NAME YOUR NEW CHARACTER screen.

On the NAME YOUR NEW CHARACTER screen, type MyBPShooterCharacter into the Name field.

Figure 1.15 – Adding the MyBPShooterCharacter C++ class

Please pay attention to the path where the header and the source files will be placed. They look different from the MyShooter project because the C++ node hasn’t been created yet. Don’t worry