Creating an RTS Game in Unity 2023 - Bruno Cicanci - E-Book

Creating an RTS Game in Unity 2023 E-Book

Bruno Cicanci

0,0
39,59 €

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

Mehr erfahren.
Beschreibung

Building a successful real-time strategy game is challenging, because of both the complex mechanics and the need to strike a balance between different elements, ensuring that players enjoy creating and executing strategies against the game's AI.
Creating an RTS Game in Unity 2023 will teach you how to install and set up the Unity game engine, create a new 3D project, and build a level editor to make it easier to modify and add maps to a game. The RTS game will start to take shape while you learn to implement different core systems such as melee and ranged battles, unit spawners, camera controls, dynamic mapping generation, basic enemy AI, and the pathfinder algorithm. You'll also get to grips with implementing command units to perform actions, crafting and producing resources, basic physics and collision detection, and building an RTS game from scratch using C# and the latest features of the Unity game engine.
By the end of this book, you’ll be able to make professional and high-quality end-to-end RTS games using the best practices and techniques from the gaming industry.

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

EPUB
MOBI

Seitenzahl: 754

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.



Creating an RTS Game in Unity 2023

A comprehensive guide to creating your own strategy game from scratch using C#

Bruno Cicanci

Creating an RTS Game in Unity 2023

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: Nitin Nainani

Senior Editor: Hayden Edwards

Technical Editor: K Bimala Singha

Copy Editor: Safis Editing

Project Coordinator: Aishwarya Mohan

Proofreader: Safis Editing

Indexer: Hemangini Bari

Production Designer: Vijay Kamble

Marketing Coordinators: Namita Velgekar and Nivedita Pandey

First published: October 2023

Production reference: 2030424

Published by Packt Publishing Ltd.

Grosvenor House

11 St Paul’s Square

Birmingham

B3 1RB

ISBN 978-1-80461-324-5

www.packtpub.com

To my mother, Sonia, and my father, Paulo, who gave me the gift of dreams and the ability to realize them. To my little sister, Paula, for always being there for me. To the dear memories of my grandfather, Rafael, and my grandmothers, Helena and Olivia, whose lessons I will never forget. To my lovely wife, Luci, and our beloved cats, Thomas and Abel, for their love, support, and encouragement.

– Bruno Cicanci

Contributors

About the author

Bruno Cicanci is a software engineer and game developer, with a BS computer science degree and professional experience in different technologies and platforms. Since 2009, he has worked at prestigious game studios such as Glu Mobile, Electronic Arts, and Aquiris, and has helped develop and publish many games, mainly using Unity for mobile devices.

Currently, Bruno develops games and reusable technologies at Ubisoft. Plus, he writes about game development on his personal blog, which has led him to present many talks at universities and events.

Originally from São Paulo, Brazil, Bruno currently resides in London, UK, with his wife and two adorable cats.

I want to thank the amazing team at Packt who helped me write and publish my first book.

About the reviewer

Prajwal G is a game developer who has been enchanted by the world of gaming since childhood. He started learning Unity for fun while at university, and since then, he has created a diverse range of 2D and 3D games, including educational odysseys, captivating kids’ adventures, epic RPGs, and action-packed open worlds. Game development is his passion, and every line of code is an expression of dedication to the art of gaming.

Table of Contents

Preface

Part 1: Foundations of RTS Games

1

Introducing Real-Time Strategy Games

What is a real-time strategy game?

Classic examples

Modern games

Understanding the game and level design of an RTS game

Character

Camera

Control

Creating a game design document

Game outline

World

Characters

Enemies and bosses

Gameplay overview

Game experience

Mechanics and modes

Summary

Further reading

2

Setting Up Unity and the Dragoncraft Project

Technical requirements

Downloading and configuring the Unity Editor

Using Visual Studio Code as the default IDE

Importing and organizing assets from the Unity Asset Store

Summary

3

Getting Started with Our Level Design

Technical requirements

Setting up our base scene

Scenes

Lights

Camera

Ground foundation

Level scene

Creating the first map layout using Prefabs

Creating a custom group of Prefabs

Using ScriptableObjects to configure the map

Creating ScriptableObjects for game configuration

Creating ScriptableObjects for level configuration

Adding a custom editor for the level configuration

Creating a map editor to speed up map creation

Controlling the camera

Summary

Further reading

4

Creating the User Interface and HUD

Technical requirements

Using Canvas for a responsive UI

Setting up the UI and HUD using Prefabs

Creating the MenuButton GameObject and popup

Displaying the resources counter

Adding the action buttons

Creating the details panel using a custom camera

Rendering the minimap

Loading the UI scene additively

Summary

Further reading

Part 2: The Combat Units

5

Spawning an Army of Units

Technical requirements

Configuring the unit ScriptableObject

Spawning units using the Object Pooling pattern

Implementing the Object Pooling pattern

Creating a BaseSpawner class

Updating the UI using the Message Queue pattern

Implementing the Message Queue pattern

Creating the message interface

Implementing the warrior unit spawner

Creating the resource type

Updating the UI

Creating a debugging tool for the Editor

Creating the Object Pool for the Warrior unit

Creating the debug script

Summary

Further reading

6

Commanding an Army of Units

Technical requirements

Preparing the Prefabs and UI

Adding more debug options

Preparing the Prefabs and UI

Drawing the selected area in the UI

Preparing the level scene

Selecting the units

Setting a custom color for the selected units

Defining the unit selector component

Moving the units

Summary

Further reading

7

Attacking and Defending Units

Technical requirements

Updating the UI with the selected units

Setting up the selected unit details

Setting up the selected unit actions

Attacking and defending with units

Setting up layers and collisions

Updating the UI

Attacking and playing other animations

Adding the new Mage unit and ranged attack

Creating the data, object pool, and spawner

Setting up ranged attacks with fireballs

Summary

Further reading

8

Implementing the Pathfinder

Technical requirements

Understanding the pathfinder

The Greedy Best-First and A* algorithms

The NavMesh

The Unity AI Navigation package

Implementing the pathfinder using the NavMesh

The NavMesh component

The NavMesh Agent component

The NavMesh Obstacle component

Debugging the NavMesh

Summary

Further reading

Part 3: The Battlefield

9

Adding Enemies

Technical requirements

Configuring the enemies

Spawning the enemies

Creating the enemy messages

Creating the enemy component

Creating the enemy spawner

Configuring the enemy spawner

Testing the enemy spawner

Damage feedback in the UI

Managing the damage feedback

Fading the text over time

Setting up the Prefabs for the damage feedback

Testing the damage feedback

Summary

Further reading

10

Creating an AI to Attack the Player

Technical requirements

Updating the physics settings

Calculating the damage

Adding a base class for the data

Adding a base class for the characters

Updating EnemyComponent

Updating UnitComponent

Adding damage to ranged attack

Managing the collision and chase behavior

Creating the collision component

Creating the Enemy NavMesh

Updating Unit’s NavMesh

Implementing the character life cycle

Summary

Further reading

11

Adding Enemies to the Map

Technical requirements

Creating spawn points

Adding fog on the map

Adding a new layer and updating cameras

Creating the fog component

Creating the material and Prefab for the fog

Updating the Level Manager

Patrolling the area

Summary

Further reading

Part 4: The Gameplay

12

Balancing the Game’s Difficulty

Technical requirements

Writing unit tests

Setting up the UTF

Creating the first test script

Adding more test scripts

Using unit tests to simulate battles

Simulating a battle against a single enemy

Simulating battles against multiple enemies

Balancing the battle difficulty

Summary

Further reading

13

Producing and Gathering Resources

Technical requirements

Generating resources

Managing the player’s inventory

Producing resources automatically

Gathering resources

Adding the new Resource layer

Producing resources manually

Testing the resources

Summary

Further reading

14

Crafting Buildings and Defense Towers

Technical requirements

Crafting and upgrading buildings

Dragging and dropping buildings

Configuring the Resource Store

Creating the Resource Store UI

Creating the Store UI

Training units

Configuring the Unit Store

Creating the Unit Store UI

Testing the Unit Store

Defending with towers

Adding the Tower model

Adding the new Tower layer

Adding the Tower as a unit

Testing the Defense Tower

Summary

15

Tracking Progression and Objectives

Technical requirements

Setting up objectives

Tracking objectives

Creating the Objective component

Creating the Objectives UI

Pausing the game

Winning or losing the game

Adding the Game Over popup

Summary

Further reading

16

Exporting and Expanding Your Game

Technical requirements

Exporting Dragoncraft for desktop

Preparing the Editor scripts

Exporting the desktop build manually

Creating a build system

Adding more platforms

Expanding Dragoncraft

Adding music and sound effects

Adding more content

Summary

Further reading

Index

Other Books You May Enjoy

Part 1: Foundations of RTS Games

In this first part of the book, you will learn what a real-time strategy game is and see a short game design document of Dragoncraft, the RTS game we are going to develop throughout this book. Then, you will learn how to install the Unity Engine and set up a new project, as well as how to import packages from the Unity Asset Store that we will use to build our game.

After having the Unity project set up and all packages imported, you will learn how to create a level, build a custom editor tool to configure the GameObjects on the map, implement camera movement, and everything else that is needed for our level design. You will also learn how to create a flexible UI and HUD on Unity, and how to use multiple cameras to render 3D GameObjects in the UI.

This part includes the following chapters:

Chapter 1, Introducing Real-Time Strategy GamesChapter 2, Setting Up Unity and the Dragoncraft ProjectChapter 3, Getting Started with Our Level DesignChapter 4, Creating the User Interface and HUD

1

Introducing Real-Time Strategy Games

Video games are highly complex graphic software, and, at the same time, an art form used to create interactive and immersive experiences. They are not easy to develop and most of them are difficult to master. Real-time strategy (RTS) games require the player to think ahead regarding each possible movement that they are going to perform, as well as what the opponent might do in response. If you then add a real-time constraint to this, you get one of the most challenging and competitive video games possible.

In this first chapter, you will be introduced to the definition of an RTS game and analyze a few classic examples of this sub-genre so that you understand what the main game mechanics and features are. This chapter will also cover the game and level design that defines the game project that is going to be developed throughout this book.

So, in this chapter, we will cover the following topics:

What is a real-time strategy game?Understanding the game and level design of an RTS gameCreating a game design document

What is a real-time strategy game?

An RTS game, as its name suggests, is a subgenre of strategy game where the player plays in “real time” without needing to wait a turn. This becomes especially challenging when the match starts to build up and the player needs to handle multiple situations, make quick decisions regarding what units to train, what orders to give to the trained units, how to gather and produce more resources, where to explore in the map, where to search for the objective and, of course, try to figure out where the enemy is and what their next move will be.

Classic examples

Released by Blizzard in 1998, StarCraft is one of the most popular RTS games to this day and has a long history of professional players competing against each other in worldwide championships (it was also one of the very first esports). The classic StarCraft gameplay in the remastered version was released in 2017 and is still one of the benchmarks of this strategy sub-genre, as well as Warcraft III, which was released in 2002.

Even though these games can be listed as the most popular of this genre, it is no doubt that other games were the pioneers in many forms of gameplay and mechanics that we define as RTS today. Developed by Westwood Studios and released by Virgin Games in 1993, Dune II was the very first RTS game to introduce resources gathering, base and unit buildings, construction dependencies, and different factions with unique weapons – all features that are now part of any RTS game. Dune II was not the first RTS game, but it was the game that helped define this genre.

Another RTS game that should be mentioned is the Age of Empires series, started in 1997, which was a combination of Warcraft and Civilization, the latter being a turn-based strategy (TBS) game.

Modern games

The RTS games that were released in the 1990s defined the base of the genre, but many other games expanded the features, gameplay, and mechanics, creating sub-genres such as real-time tactics (RTT) and Explore, Expand, Exploit, Exterminate (4X).

Dune: Spice Wars is a great example of a modern 4X RTS game that was released in 2022 as early access on Steam. Following in the footsteps of Dune II, this game contains all the great features that are expected from this genre with modern graphics. Company of Heroes, a World War II-based game, also pushed RTS games further with real-time physics and destructible environments.

RTS games are also the foundation of the very popular multiplayer online battle arena (MOBA) that was born as a Warcraft III mod in 2003 called Defense of the Ancients (DotA). Years later, DotA 2 (2013) and League of Legends (2009) were released and defined a new strategy sub-genre.

There are so many great classic and modern RTS games that we could cover an entire book on them, but I had the difficult task of selecting a few of them to illustrate their beginnings and evolution.

Now, we are going to look at the features that most of these games share.

Understanding the game and level design of an RTS game

Game design is the art of creating the idea and the rules that describe what the game is and, more importantly, making it a fun and remarkable experience for the player. Level design is a specialization of game design that is responsible for level creation.

We can define most of the gameplay and mechanics of a video game by looking at the three Cs: character(s), camera(s), and control(s). In the following sections, we will see how these three aspects of a game help tighten the gameplay because they all work together and should move alongside each other.

Character

Characters in an RTS game are represented by the units that the player can use in the game, as well as the enemies that are spread across the map. Usually, the main game plot is not attributed to one character in an RTS game but rather to the collective units that the player, as the commander, can control to perform actions. The player will think about the strategy first, and then use the units as a tool to achieve what was planned.

Units can be controlled to explore the map, attack enemies, defend the settlement, collect resources, and create buildings. The characters here are not important, nor do they have a great impact on the game, but it is part of the strategy that the player built.

In a few RTS games, there are characters such as heroes or infamous bosses that have distinct personalities that can drive the story of the game. In this case, the player is still controlling nameless units, but there is a hero to fight alongside or a greater evil to be defeated.

Camera

The camera is one of the most characteristic aspects of an RTS game. Besides the ability to move around the map at will, as we are going to see in the next section, the camera usually shows the top view of the territory, and all parts that are not explored yet are covered with fog; this means that the player can see the unexplored regions of the map and send units to explore them, clearing away the fog.

It is also possible to zoom in and out on the map, which helps give a macro view of the battlefield before you take micro-decisions to attack, defend, build, produce, and gather resources. The ability to move the camera quickly using the mini-map is very important and useful in the late stages of the match where a lot of things are happening at the same time across the territory.

An RTS map usually has a starting point (the blue X) and shows the enemy base that must be conquered or destroyed (the red X). Only the player’s initial position is shown uncovered in the camera, and many other hidden objectives or resources are hidden in different locations on the map, so the player will find something interesting in any direction that they move.

Control

The player control is rather basic in an RTS game but it’s this simplicity that helps players make the best and quickest decisions. Controlling the camera is vital to decide where to go or to monitor what the enemies are doing, and with easy access using the mini-map, players can control the camera quickly. Besides the camera, the player can also control the troops by selecting one or more units and giving them a command – this command could be to gather nearby resources, attack an enemy, or just move to a position and wait idly for any enemy threat.

Selecting units or a building will display different options in the UI so that the player has all the information required to decide on the next steps. All control is usually done by using the mouse’s left and right buttons and the cursor movement on the screen. Some games were created or adapted to consoles and these controls were translated to the gamepad. The same happens for mobile RTS games and touchscreen controls, which work great since they’re very similar to mouse control.

Now that we know what an RTS game is and what kind of game and level design is involved, we need to define the game that will be developed by you throughout this book. The best way to define the scope of the project is by creating a simple game design document.

Creating a game design document

A game design document (GDD) is a document written by the game designer that defines the scope of the game, from the characters and story to the gameplay and mechanics used by the player. There are different approaches to elaborate a GDD, from straightforward text to dense documentation full of details and explanations. We are going to use a simple but effective method that consists of defining the bare bones of our game with enough details that will help us develop our game with all the features in mind.

In the following sections of this chapter, we are going to define the game that will be developed throughout this book: Dragoncraft.

Game outline

Dragoncraft is an RTS game where the player will defend a small village against the dragons that are scattered through the land. Before facing the mighty dragons and destroying their nests, the player needs to expand the small village by creating new buildings and training an army to both attack and defend the village. To grow the village, the player will need to gather and produce resources while defending the territory against orcs and exploring the lands beyond the village to find even more resources. It is important to create the right strategy to explore and defend before the dragons start to hunt for more food.

World

The level has a map showing land with a few forests, villages, and the dragon’s nest. Villages can contain both enemies and extra resources for the player, so it’s well worth the adventure to explore and raid them. Each level will have a map that increases the difficulty, giving the player more challenges.

When the game starts, the entire map is covered by clouds, so the player will have to send units to explore and review the map. The player must defend the village; otherwise, the enemies will kill all the units and take the resources away, making the player lose the game.

Characters

The player’s army can be trained to be bigger and stronger based on what buildings and levels the player crafted in the village. There will be two basic types of soldiers: the Footman, a melee combatant, and the Wizards, who can cast powerful spells from a safe distance:

Figure 1.1: Mini Legion Footman PBR HP Polyart by Dungeon Manson, ©2022 Unity Technologies

The units can be generated and upgraded in the training camp using resources that the player collects. When both units are combined and used wisely, they can form a very versatile army.

Enemies and bosses

Hidden in other villages across the map, the enemies will wait for the player’s units to approach their territory. The orcs will attack the units with no mercy and, if they defeat the player’s units, they will follow the trail back to the player’s village to raid it. There are a few errant orcs that will spawn in different locations and search for the player’s village, attacking at first sight:

Figure 1.2: Mini Legion Grunt PBR HP Polyart by Dungeon Manson, ©2022 Unity Technologies

As the player starts to upgrade the units, the orcs will also become stronger by spawning new and improved versions. A few variables of the orcs with different colors and stats will keep the game challenging for the player.

The player’s objective is to find and kill the dragon and destroy the dragon’s nest. A few orcs will help the dragon, which is like the level boss, to defend the nest and attack the player. Each level will have a different dragon with different stats:

Figure 1.3: Dragon the Soul Eater and Dragon Boar by Dungeon Manson. ©2022 Unity Technologies

If the player is taking too much time to find the dragon’s nest, a new dragon will be spawned to protect the nest while the other dragon goes to look for the player on the map. The dragons are quite strong and it will take a few unit upgrades and a large army to defeat them. Unlike the orcs, the dragon will not abandon its nest to look for the player’s village if it kills all player units sent to explore the map.

Gameplay overview

Dragoncraft is an RTS game where the player starts in a small village with a couple of units and very limited resources. The player will need to expand their village by gathering resources and training more units to be prepared to find and kill the dragon hidden on the map. The player gives commands to the units to gather resources, build or upgrade a construction, and train more units.

When the game starts, only the village is visible in the top-down camera, and the player must select and command the units to go explore the map and clear the way. The mini-map on the UI is a great tool to quickly move the camera to a desired location on the territory and will be very helpful in the late game.

Enemies, controlled by the game’s AI, are hidden across the map and will attack as soon as they see the player’s unit approaching. Also, from time to time, a few enemies will start to explore the map and find the player’s village to raid and loot the resources. The player must explore and find the dragon hidden on the map, defeat it, and destroy the nest. If they take too much time to find the dragon, the dragon will start to look around and explore the map, but the nest will be very well guarded by another dragon.

The player oversees the village and gives out orders to make the units perform activities. The player mainly completes input via the mouse, in which they can do the following actions:

Left-click to select a unit or buildingLeft-click and drag to select unitsWhen the units are selected, right-click to set a movement target (when the target is in a valid position) or attack an enemyWhen units or a building is selected, the UI at the bottom of the screen will change to display information and extra actions availableMoving the mouse cursor in any direction will also move the top camera

Besides the mouse, the player can use the Escape key to pause the game, and the Space key to move the camera back to the village.

Game experience

The player must have the feeling that they need to think and act quickly as the enemies are doing the same to raid the village. All tools and resources available should be useful for the player to make decisions and see the outcome so they can plan the next steps.

The game should be balanced in such a way that a series of wrong decisions may lead the player to lose the game, but at the same time, the right decisions lead them to victory. The victory path should be challenging and not a shortcut that will make the player so strong that nothing can defeat them. In the end, the player must feel rewarded by the experience and want to play again but on a slightly more difficult map.

Mechanics and modes

The gameplay mechanics are the classic RTS actions that the player must choose wisely because each one takes some time to complete, and the units can’t be interrupted once they start an action. The selected units can perform different actions, such as the following:

Gather resources from a location and bring them to the main village buildingBuild or upgrade constructionsAttack an enemyMove and stay idle in one specific spot until another command is given

There are different types of buildings and they can all be upgraded. These buildings are required to store resources, train new units, and unlock new upgrades. Besides the main hut, all other buildings must be constructed using at least one unit, and the cost of resources is displayed in the UI. The buildings are as follows:

Town Hall: This building is responsible for storing resources. Upgrades will increase the number of resources received and unlock other buildings.Barracks: This building is responsible for the units’ training. Upgrades will unlock different units such as the Wizard for ranged combat and stronger units to be trained.Defense Tower: This building is used for defense. If the enemies enter the tower area, a ranged attack will hit them.Blacksmith: This building is used to craft strong weapons and armor for the units, giving them more means of attack and defense.

Once the player finds and defeats the dragon, and destroys the dragon’s nest, a new game will be offered to the player, where they can choose to play the same map again or the one that was unlocked by completing the current one. Each map is predefined, and no random levels are generated.

The GDD is a great resource for describing what the game is about and the gameplay and mechanics that make it a great game. It is also important to let the game developers know what to create and how everything connects to make a memorable experience for the player.

Summary

In this chapter, we learned what an RTS game is and what the main gameplay mechanics that define this genre are. We also looked at a few examples of such features that led to our own GDD, which contains the outline of the game that will be developed through this book: Dragoncraft.

In Chapter 2, Setting Up Unity and the Dragoncraft Project, we are going to download and install the Unity editor, learn how to set up Visual Studio Code to work with the engine, and how to create a new project and organize all assets that will be downloaded and used in later chapters.

Further reading

For more examples of RTS games and their history, check out these links:

Real-time strategy: https://en.wikipedia.org/wiki/Real-time_strategyList of real-time strategy video games: https://en.wikipedia.org/wiki/List_of_real-time_strategy_video_games

You can learn more about game design by reading these excellent books:

Schell, Jesse. The Art of Game Design: A Book of Lenses. 3rd ed. (2019) CRC PressRogers, Scott. Level Up! The Guide to Great Video Game Design. 2nd ed. (2014) WileyFullerton, Tracy. Game Design Workshop: Playcentric Approach to Creating Innovative Games. 4th ed. (2018) CRC Press

2

Setting Up Unity and the Dragoncraft Project

Today, many different game engines can be used to develop games, and most of them are free to use or have a free license until you start making thousands of dollars in profit. Even with many options available, the Unity engine is probably the most popular choice for both new and experienced game developers, capable of making projects from small games, all the way up to AAA games with advanced features that push the hardware to its limits.

In this chapter, you will learn how to download and install the Unity game engine, including the recommended version and modules to install, as well as how to configure Visual Studio Code as the default integrated development environment (IDE) and install the required extensions. This chapter will also show you how to download and import all content required for building our RTS game, Dragoncraft, from the Unity Asset Store.

By the end of this chapter, you will have learned how to set up and organize a Unity project to make it easier to work on, as well as how to keep it organized as we advance through the development of the game by adding code and assets.

In this chapter, we will cover the following topics:

Downloading and configuring the Unity EditorUsing Visual Studio Code as the default IDEImporting and organizing assets from the Unity Asset Store

Technical requirements

To complete this chapter and create Dragoncraft, here is the software you need to install:

Visual Studio Code for the C# programmingUnity Engine 2023.1 (or later)

The project setup for this chapter, along with the imported assets, can be found on GitHub at https://github.com/PacktPublishing/Creating-an-RTS-game-in-Unity-2023.

The assets from the Unity Asset Store that have been used in this project can be found at https://assetstore.unity.com/lists/creating-a-rts-game-5773122416647.

Downloading and configuring the Unity Editor

To get started, we will need to install Unity Hub, which is the entry point for installing the Unity Editor so that we can create and load projects. Head to https://unity.com/download and click on the Download for Windows button if you have a Windows setup or the Download other versions button for the macOS installer and Linux instructions.

Once downloaded, follow the installer’s instructions to add Unity Hub to your system. Next, click on the Installs tab and then click on the Install Editor button. From the following screen, select the latest version available for Unity, which is 2023.1 at the time of writing, or any later editions:

Figure 2.1 – Install Unity Editor

As soon as you click on the Install button, you will be presented with the following screen, where you can select the modules you would like to install:

Figure 2.2 – Unity modules

By default, Unity will install the desktop module, which is mandatory, and have pre-selected both Visual Studio Community and Documentation to be installed.

Clicking on the Install button will download and install all the selected modules for the desired Unity version. This can take some time, depending on your internet speed:

Figure 2.3 – Unity 2023.1 installed

Note

At this point, no other modules are required. However, once installed, any extra module can easily be installed using Unity Hub by clicking on the configuration (cog) icon to the right of the Unity Editor.

While this process is happening, you can proceed to the next section and install our IDE.

Using Visual Studio Code as the default IDE

Visual Studio Code is a lightweight but powerful IDE that provides extensions to expand the supported programming languages and technologies you want to use. It is available for Windows, macOS, and Linux. Go to https://code.visualstudio.com/ and click on the Download button. Select the option that matches your operating system:

Figure 2.4 – Visual Studio Code download

Once downloaded, unzip the file and double-click it to launch the IDE. On the left-hand side of the screen, select Extensions and search for C#, as shown in the following screenshot. Click Install to add C# support to Visual Studio Code:

Figure 2.5 – Visual Studio Code C# extension

Now that Visual Studio Code has been installed and configured, we can create a new Unity project and set it up as the default IDE.

Launch Unity Hub and click on the New Project button in the top-right corner. Then, select the 3D Core template, which is just an empty project with pre-configured settings for 3D projects. Next, type your project’s name, which in this case is Dragoncraft, and select the desired location for the project to be created:

Figure 2.6 – New project settings

After clicking on the Create project button, Unity will start to create and set up the project for the first time, which can take a few minutes depending on your system.

The last step is to select Visual Studio Code as the default IDE via Unity Editor. To set it up, go to Edit | Preferences (on macOS, the Preferences option is located in Unity’s main menu). On the opened screen, select External Tools from the left-hand side; then, from the External Script Editor option on the left side, select Visual Studio Code from the list of options:

Figure 2.7 – External Tools

Visual Studio Code is a professional tool that can be used to develop any kind of project. However, you can also use Visual Studio 2022, which is a good, free IDE for personal use. However, keep in mind that it is heavier in both size and performance and, in this book, we will not be using any specific feature of Visual Studio, so Visual Studio Code is the best option for our RTS Game project.

If you wish to install Visual Studio 2022 and do not have it already, it is available on both Windows and macOS: https://visualstudio.microsoft.com. Follow the instructions at the aforementioned link to install the IDE.

Once installed, you can select it as the default IDE via the Unity Editor by going to the same settings screen as shown in Figure 2.7. You might need to close and re-open the project to see Visual Studio in the list of options or use the Browse option to look for the application.

Now that we have downloaded the Unity Editor, the new project has been created, and we have set up Visual Studio Code as the default IDE, we can start to import and organize the assets required to build our game.

Importing and organizing assets from the Unity Asset Store

Now that all the configuration is done for both the Unity Editor and the IDE, we can use our empty project to get started with our RTS game development. This book will cover all the coding aspects of creating an RTS game, but since we are not going to create any art, the free assets from the Unity Asset Store will be used.

Go to the Unity Asset Store (https://assetstore.unity.com) and create a free account that will allow you to download and import the assets in the Unity Editor.

Next, access this public list, which contains all the assets needed to develop our RTS game in this book (https://assetstore.unity.com/lists/creating-a-rts-game-5773122416647) and click on the Add to My Assets button for each of the six assets. Every time you click that button, a pop-up message stating Unity Terms of Service will be displayed for you to accept the terms of service before the asset is added to your account.

Once added, you have the option to click on the Open in Unity button. If you have the Unity Editor open, you will be shown the package manager and the asset that’s been selected, ready to be downloaded and then imported:

Figure 2.8 – Asset list in the Unity Asset Store

You should be able to see all assets in the Unity Editor, on the Package Manager screen, as shown here:

Figure 2.9 – Downloading and importing assets from the Package Manager screen

You will have a Download button next to each asset that you need to click so that Unity will download that package into your system but not into your project. As soon as the download is finished, you will be able to see an Import button, which will import the package into your opened project. This needs to be done for each package so that all the assets are imported into the project.

If everything worked correctly, you should have the following folders inside your Assets folder:

FreeDragonsMini Legion Footman PBR HP PolyartMini Legion Grunt PBR HP PolyartMini Legion Lich PBR HP PolyartMini Legion Rock Golem PBR HP PolyartRPGPP_LTScenes (this one is created by default when you create a new project)

Now, to keep it organized, let’s create a new folder by right-clicking Assets in our Project window. Then, from the menu, select Create | Folder and name it ThirdParty so that we know those assets were not created by us in this project. Once you’ve done this, you should have a project structure similar to the following:

Figure 2.10 – Project structure after importing the necessary assets

With all of this done, we are ready to get started with the first coding part of Dragoncraft in the next chapter. You will probably do most of the steps shown in this chapter only once since that is all you need to develop any game using the Unity Editor and Visual Studio Code as the default IDE. You can always go back to Unity Hub and download new versions or edit an installed version to add more modules, such as Android and iOS, for mobile game development.

Summary

In this chapter, we learned how to download, install, and set up the Unity Editor using Unity Hub. We also downloaded and installed Visual Studio Code, imported the required extension, and configured it as the default IDE for the Unity Editor. In the end, we imported all the free assets required from the Unity Asset Store into our newly created project and organized it.

In Chapter 3, Getting Started with Our Level Design, we are going to start coding our map editor and create a few levels using this tool, ScriptableObjects, and the assets we imported from the Unity Asset Store. We will also configure the main scene, lights, camera movement, and mini-map navigation – one of the key gameplay features of our RTS game.

3

Getting Started with Our Level Design

RTS games have a few characteristics and requirements that are very specific to them – the camera setup and movement have an industry standard to follow with some variations; the levels have many assets that are used to set the mood and predefine the available paths for the player to explore; and also, due to the high quantity of maps and variations, a map editor tool is required to speed up the level design, matching the rules defined by the game design and the gameplay mechanics.

This chapter will introduce you to the first scripts that will be required to write C# code to achieve the features and requirements of our game as defined in the previous chapter. You will learn how to set up a game scene with the proper light and camera settings for an RTS game, as well as how to create and use Prefabs, which are reusable assets that act as a template, to develop maps for the game. We are also going to explore one of the most flexible and useful resources available on Unity, ScriptableObjects, a data container that will be crucial for developing our map editor tool and will make it easier to build different maps.

By the end of this chapter, you will know how to use many useful resources and APIs from Unity that are applied to not only RTS games but all other kinds of games too. Everything developed in this chapter forms the building blocks that we will use to create the foundation of our Dragoncraft game, and introduces the tools that you can use later to expand the project even further with your own levels.

This chapter will cover the following topics:

Setting up the base scene on Unity for an RTS gameCreating the first map layout using PrefabsUsing ScriptableObjects to configure the mapCreating a map editor to speed up map creationControlling the camera in RTS games

Technical requirements

The project setup in this chapter with the imported assets can be found on GitHub at https://github.com/PacktPublishing/Creating-an-RTS-game-in-Unity-2023/tree/main/Dragoncraft/Assets/Chapter03.

All scripts and scenes created in this chapter are available there, but we are also going to use the assets imported in the previous chapter, which are in the Chapter02 folder.

Setting up our base scene

Before we create our first level, we need to set up the base scene of the project, which will be used by our map editor to populate the map with the assets we are going to define in the configuration for each level. In addition to the base scene for every new level, we will also create a Playground scene, which, as the name suggests, will be used a lot during the game production so we can develop and test features freely without breaking our levels or being limited to the configuration we have.

Scenes

When we created the new Unity project following the instructions from the previous chapter, Unity automatically created a first scene for us called Sample Scene inside the Scenes folder, which is basically an empty scene with a standard main camera and directional light. Right-click on the scene and select Rename – we’ll change it to Playground, as you can see here:

Figure 3.1 – Renaming the scene to Playground

If you do not have a scene or the Scenes folder already, you can create both by right-clicking on the Assets folder and selecting Create | Folder, and giving it the name Scenes. Then, right-click on the newly created folder, select Create | Scene, and name it Playground.

Now that we have our scene for the Playground, let’s set it up properly so we can create the scene for our first level from this one without having to do this configuration more than once.

Lights

Usually, the Light settings generated by default when creating a new scene are all properly set up for most types of games and we do not need to change them at the beginning of the development. Later, we might have multiple light sources with different types to have a more robust illumination in our scene, but for now, we can leave the light as a single directional light in the scene.

You can inspect the Light settings in the scene by left-clicking on the Directional Light object in the Hierarchy window – the settings will be displayed in the Inspector window. For our RTS game, the default settings work very well out of the box; just make sure the settings are the same as in the following figure:

Figure 3.2 – Directional Light settings

For the Directional Light type, the only Transform property that changes the way the light reflects and casts shadows is Rotation. You can play with the values to find what looks better for your scene; however, the values shown in Figure 3.2 are the ones we are going to use for all levels in our RTS game.

Camera

The camera is one of the most important items in an RTS game because it is also used by the player as a tool to help make strategic decisions since they can move it around the map during gameplay. We’ll talk about camera movement later in this chapter, but for now, we are just going to set up the configurations that will not change while moving or zooming around the map, which are the Projection and Transform properties.

In the Hierarchy window, left-click on the Main Camera object to show the details in the Inspector window. Now, set the Transform values for both Position and Rotation to match the values shown here:

Figure 3.3 – Main Camera settings

The next couple of changes must be made to the Camera component, which is already attached to the MainCamera object. Change Projection to Orthographic – using this projection, the perspective is removed and objects do not get smaller with distance (which works best for RTS games). Then, set the Size property as 10 – this will be used to adjust the player’s camera zoom during gameplay. All the other settings can be kept as the default values.

Ground foundation

The Playground scene is almost ready to be used, but we are still missing one last thing to make it usable for developing and testing our levels: adding a plane to be the ground foundation of the scene. A plane is a built-in 3D object that represents a flat surface with a Mesh Renderer component, which can be used to set textures or materials, and a Mesh Collider to detect collision.

Note

The Mesh Renderer is a component that renders a mesh, which is the main graphic primitive of Unity. The Mesh Collider generates a physics collider based on the mesh attached to the component.

To add a plane to the current scene, go to GameObject | 3D Object | Plane. Alternatively, you can right-click on the Hierarchy window and select the 3D Object | Plane option.

Once added, make sure to set the Transform values for both Position and Rotation to (0, 0, 0) and Scale to (10, 10, 10) so that the plane is big enough to place assets and build the level. Transform is a Unity component that determines the position, rotation, and scale of a GameObject in the scene, and we are going to use it many times to position the GameObjects in the 3D world.

The following figure shows the expected outcome (do not forget to save the scene after adding the plane and making the changes):

Figure 3.4 – Plane added to the scene with Scale set to (10, 10, 10)

For the Playground scene, we can leave the plane white to make it easier to identify that it is a test or development scene, but for the real levels, we will be creating materials to change the color and we will create different map sizes by tweaking their scale (the scale of the plane will be referred to as our map limit, which is what the player will be able to see and interact with without moving out of the boundaries).

Level scene

Now that we have our Playground scene, we can make a copy of it to set as our first game level. To do that, select the scene in the Project view and press Ctrl + D on Windows (or Command + D on macOS) to duplicate it. Then, rename the new copy Level01. At this point, you should have two scenes, as shown here:

Figure 3.5 – The Playground and Level01 scenes

Double-click on the Level01 scene to open it – you can see the name of the opened scene in the Hierarchy window to make sure it is the correct one. To make it different from the Playground scene, we are going to add a green color to the plane using a Material asset, which has a reference to a Shader object and is used to describe the appearance of surfaces.

In the same way as we created the Scenes folder, create a new folder called Materials. Once you have that new folder, left-click on it and select Create | Material, then name it GreenGrass.

Select the newly created material, go to the Inspector window, and right-click on the white field on the right of the Albedo property, which will open a new window with a color wheel. In this window, type 669966 in the Hexadecimal field, and you should see a green color appear:

Figure 3.6 – Setting the material color

Finally, go back to the Hierarchy window and select Plane to see the details in the Inspector window. In the Mesh Renderer component, Plane has Default-Material as the material used. Click on the white circle on the right of the material name to open the Select Material window and search for the GreenGrass material that we just created. After selecting it, the plane will become green. This is the most common way to change the color of a 3D object, and you can have multiple materials to use different colors as well.

Figure 3.7 – Applying the green material to the plane

Do not forget to save the scene after setting the material! Now, with everything that we set up in this section, we can move forward and start adding assets to build our first level.