Game Development with Unity for .NET Developers

By Jiadong Chen
    What do you get with a Packt Subscription?

  • Instant access to this title and 7,500+ eBooks & Videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Free Chapter
    Chapter 1: Hello Unity
About this book

Understand what makes Unity the world’s most widely used real-time 3D development platform and explore its powerful features for creating 3D and 2D games, as well as the Unity game engine and the Microsoft Game Dev, including the Microsoft Azure Cloud and Microsoft Azure PlayFab services, to create games.

You will start by getting acquainted with the Unity editor and the basic concepts of Unity script programming with C#. You'll then learn how to use C# code to work with Unity's built-in modules, such as UI, animation, physics, video, and audio, and understand how to develop a game with Unity and C#. As you progress through the chapters, you'll cover advanced topics such as the math involved in computer graphics and how to create a custom render pipeline in Unity with the new Scriptable Render Pipeline, all while optimizing performance in Unity. Along the way, you'll be introduced to Microsoft Game Dev, Azure services, and Azure PlayFab, and using the Unity3D PlayFab SDK to access the PlayFab API.

By the end of this Unity book, you'll have become familiar with the Unity engine and be ready to develop your own games while also addressing the performance issues that you could encounter in the development process.

Publication date:
May 2022
Publisher
Packt
Pages
584
ISBN
9781801078078

 

Chapter 1: Hello Unity

Before we get started with using Unity to develop games, I think it's good to first understand Unity itself. Many people, especially those who are interested in games and game development, know that Unity is a widely used game engine, and you may have played many games developed with Unity. But you may not be familiar with how to use Unity to develop games. For example, there are many different Unity versions available, so how do you choose the version that suits you? Unity provides different subscription plans, but which subscription plan is right for your situation?

If you have never used Unity before, it is necessary for you to learn how to use the Unity Editor first. In addition to the Unity Editor, what features does the Unity engine provide to help game developers develop games? It is also important to know the features in Unity. If you are a .NET developer, then it's likely that you are familiar with Visual Studio. You need to know how to use Visual Studio to develop a Unity game. But developing a Unity game is different from developing a .NET application.

Am I asking too many questions? Don't worry – this chapter will help you answer them.

In this chapter, we will introduce how to choose the right release of Unity and provide an overview of how to download and install Unity via the Unity Hub or the Unity installer. Then, we will choose the right subscription plan for your situation. At this point, you should have installed Unity and opened the Unity Editor.

If you have only just started using the Unity Editor, you may not know how to use it. We will first explore the Unity Editor and then discuss the different features provided by Unity. We will then introduce the .NET profiles in Unity and the scripting backend offered by Unity. Finally, we will present how to use Visual Studio to develop Unity games.

We will cover the following key topics in this chapter:

  • Getting started with the Unity Editor
  • Working with different features in Unity
  • .NET/C# and scripting in Unity
  • Building Unity games with Visual Studio
 

Technical requirements

Before starting, I highly recommend you first check whether your system can run the Unity Editor. The following table gives the minimum requirements to run the Unity Editor:

 

Getting started with the Unity Editor

Whether you are an independent game developer or work in a team for a company, you need to do two things before installing or even downloading Unity:

  • Choose the right Unity release for you.
  • Choose the right subscription plan for you.

Therefore, before introducing how to install Unity and exploring the Unity Editor, let's first introduce the Unity release and subscription plans. We hope that by reading these contents, you can find the right release for you and choose a suitable subscription plan.

Choosing the right Unity release for you

Nowadays, Unity offers two different release versions each year. They are as follows:

  • Tech Stream releases
  • Long-Term Support (LTS) releases:

Figure 1.1 – Unity releases

Figure 1.1 – Unity releases

You may not be quite sure which version of Unity is best to use in your project, so I will explain these two different releases so that you can get an idea of how to choose the right release for you.

LTS releases provide developers with maximum stability and full support for their projects, and they are the last Tech Stream releases of each year. With LTS releases, there are no new features or API changes. The updates of LTS releases address crashes, and fix bugs and any minor issues. As I mentioned at the beginning of this section, each year, Unity releases new versions of the LTS release, and each one is supported for 2 full years from the date of the announcement.

Therefore, if you are looking for performance and stability, or your project is already in production or in the middle of development, it is a good idea to use the latest LTS release version to ensure best performance and stability.

Note

At the time of writing (April 2022), there are two LTS releases, namely Unity 2020 LTS and Unity 2019.4. Unity 2020 LTS is the latest LTS release and has the same feature set as the Unity 2020.2 Tech Stream release. Alternatively, Unity 2019.4 is the legacy LTS release now.

The Tech Stream releases give developers who want to explore the latest in-progress features an option to use them to prepare for future projects. Unlike the LTS releases, a Tech Stream release will be released twice a year (typically published in the first and last quarters) and will only be supported until the next Tech Stream release is officially published.

Therefore, if you are preparing for your next project or working on prototyping and experimentation, you should try the Tech Stream releases.

Note

At the time of writing (April 2022), the latest Tech Stream release is Unity 2021.2.

By reading this section, I hope you have gained an understanding of the Unity releases, and you should be able to choose the right Unity release according to your situation.

When writing this book, I chose the latest LTS version, Unity 2020.3.

Choosing the right subscription plan for you

Unity is a widely used game engine, and many independent game developers use Unity to develop their games. But technically speaking, Unity is not a free game engine. In this section, I will introduce several different subscription plans offered by Unity. I hope that after reading this section, you can choose a subscription plan that suits your situation.

Unity offers a range of plans, from the free Personal plan for individual learners to Enterprise plans used by large organizations:

Figure 1.2 – The Plans and pricing page

Figure 1.2 – The Plans and pricing page

Because each Unity plan has different eligibility requirements, you should choose the right plan for your project. Next, I will introduce the subscription plans:

  • The Personal plan is free and includes all the basic functionality of Unity. You can choose this plan if you work as an individual and have earned less than $100,000 in revenue or funding for your Unity project in the past 12 months. In addition, if you are a student or educator, you can get additional benefits, but before that, you need to join the GitHub Student Developer Pack to be verified.
  • The Plus plan is a paid plan and offers more functionality and training resources, such as advanced cloud diagnostics and splash screen customization. If you have earned more than $100,000 but less than $200,000 in revenue from using Unity in the past 12 months, you should choose this plan.
  • The Pro plan is also a paid plan. Compared with the Plus plan, you can get more technical support from Unity by using the Pro plan. If your organization has earned more than $200,000 in the last 12 months from any source, you must use the Pro plan or the Enterprise plan.
  • The Enterprise plan is specifically for teams with at least 20 members and provides more support than the Pro plan. For example, a customer success manager from Unity will be assigned to your organization to provide guidance, orchestrate resources, and serve as an internal advocate.

I hope this section was helpful for you in choosing the right Unity plan for your situation. Next, let's download and install the Unity Editor!

Downloading and installing the Unity Editor

There are two different ways to download and install the Unity Editor. The first and recommended way to download and install Unity is to use the Unity Hub.

The Unity Hub is a management tool that can be used to manage all your Unity projects and Unity installations. We can take the following steps to install the Unity Hub and the Unity Editor:

  1. To install the Unity Hub, visit the Download Unity page at https://unity3d.com/get-unity/download:
Figure 1.3 – The Download Unity page

Figure 1.3 – The Download Unity page

As you can see in the System requirements section in the preceding screenshot, the Unity Hub supports Windows, Mac OS X, Ubuntu, and CentOS.

  1. Installing the Unity Hub is very easy; you just need to choose the folder where the Unity Hub is installed. Then, click on the Install button:
Figure 1.4 – Unity Hub Setup

Figure 1.4 – Unity Hub Setup

  1. After installing the Unity Hub, select the Run Unity Hub option and click on the Finish button to launch the Unity Hub:
Figure 1.5 – Completing Unity Hub Setup

Figure 1.5 – Completing Unity Hub Setup

I am using the latest version of Unity Hub (version 3.0.0) at the time of writing. If you have used previous versions of Unity Hub, you will find that the launch page of the new version of Unity Hub is completely different.

  1. You need a Unity account to access the Unity Editor and the Unity Hub. If you don't have a Unity account yet, then you need to create a new one:
Figure 1.6 – Unity Hub

Figure 1.6 – Unity Hub

  1. When you sign into the Unity Hub for the first time, you will be asked to add an active license, as you can see at the top of the following screenshot. Click on the Manage licenses button to open the Licenses setting panel:
Figure 1.7 – Click the Manage licenses button

Figure 1.7 – Click the Manage licenses button

  1. There are two buttons available for you to add a new license. You can click either the Add button at the top-right corner or the Add license button:
Figure 1.8 – The Licenses setting panel

Figure 1.8 – The Licenses setting panel

Then, you have different options to activate the license. We have discussed the different Unity subscription plans in the previous section:

Figure 1.9 – Add new license

Figure 1.9 – Add new license

  1. After adding the new license, we can start exploring the Unity Hub. From the Projects view, you can find a list of Unity projects that are tracked by the Unity Hub. You can also create a brand-new project by clicking the New project button at the upper-right corner of the Projects view, or you can import an existing project by clicking the Open button:
Figure 1.10 – The Projects view

Figure 1.10 – The Projects view

  1. To install the Unity Editor, open the Installs view, where you can manage the installation of multiple versions of the Unity Editor:
Figure 1.11 – The Installs view

Figure 1.11 – The Installs view

There is a list of the Unity Editors that are installed and managed by the Unity Hub. Similar to the Projects view, you can download and install a new Unity Editor, or you can import an existing Unity Editor that is not managed by the Unity Hub, such as the Unity Editor that we installed using the Unity installer.

  1. Open the Install Unity Editor panel by clicking the Install Editor button on the Installs view. Then, you will see the latest version of each release:
Figure 1.12 – Install Unity Editor

Figure 1.12 – Install Unity Editor

Note

Unity 2018 LTS has reached the end of its support cycle, so you should not install it.

We will use the latest version of the Unity 2020 LTS release, so we need to install Unity 2020.3.13f1 here:

Figure 1.13 – Install Unity 2020.3.13f1

Figure 1.13 – Install Unity 2020.3.13f1

Then, we need to select the modules that need to be installed. As you can see in the preceding screenshot, Microsoft Visual Studio Community 2019 will be installed by default, which will be our Integrated Development Environment (IDE) to develop games in Unity.

Note

If you want to change the installation location, you can change it in the Installs settings of the Preferences panel.

Once it has been downloaded and installed, we are ready to start exploring the Unity Editor!

Sometimes, you may need a specific version that is not available through the Unity Hub, such as some older Unity versions. At this point, you can also install the Unity Editor a second way, which is through the Unity installer. You can use the Unity installer to download the previous versions of Unity:

Figure 1.14 – The Unity download archive page

Figure 1.14 – The Unity download archive page

Now, follow these steps to install the Unity Editor through the Unity installer:

  1. To download a previous version of Unity, you should access the Unity download archive page at https://unity3d.com/get-unity/download/archive.
  2. Click on the Next button and choose the components of Unity that you want to download and install. The Unity installer should resemble the following screenshot:
Figure 1.15 – The Unity installer

Figure 1.15 – The Unity installer

  1. The Unity Editor is selected by default; in order to build games for different platforms, you also need to select the corresponding build support components. For example, if you want to build an Android game running on Android devices, you need to download and install the Android Build Support component:
Figure 1.16 – Choosing components

Figure 1.16 – Choosing components

  1. Click the Next button, and then you need to choose download and install locations:
Figure 1.17 – Choose Download and Install locations

Figure 1.17 – Choose Download and Install locations

  1. After specifying where to download and install these files, click the Next button to download Unity:
Figure 1.18 – Downloading and Installing

Figure 1.18 – Downloading and Installing

After the download and installation are complete, the Unity Editor icon will appear on your desktop.

Exploring the Unity Editor

The first thing we need to do is use the Unity Hub to create a new Unity project. As I mentioned in the previous section, we will create a brand-new project by clicking the New Project button at the upper-right corner of the Projects view.

Figure 1.19 – Creating a new project

Figure 1.19 – Creating a new project

As shown in the preceding screenshot, we can choose different Unity Editor versions for this new project, and Unity provides us with some built-in project templates, such as the 2D, 3D, HDRP, and URP templates. You can also download and install more templates from Unity, such as the VR template and the AR template. In the PROJECT SETTINGS section, you can set the name of the project and the location of the project.

Here, we will choose the default 3D project template and name our project UnityBook. Then, click on the Create project button. After that, the Unity Editor you previously selected will launch and open a new project for you:

Figure 1.20 – The Unity Editor

Figure 1.20 – The Unity Editor

As you can see in the preceding screenshot, the Unity Editor layout organizes the most important windows for you. Specifically, the default layout divides the editor interface into five key areas. From top to bottom, they are as follows:

  1. Toolbar
  2. Hierarchy window
  3. Scene view and Game view
  4. Inspector window
  5. Project window

Next, I will introduce these UI areas in order.

The Toolbar

The Toolbar is always at the top of the Unity Editor interface, and it consists of several groups of controls:

Figure 1.21 – The Toolbar

Figure 1.21 – The Toolbar

From left to right, the first tool in the Toolbar is the transform tools set. The transform tools are used in the Scene view and allow you to pan around the Scene and move, rotate, and scale individual GameObjects in the Scene:

Figure 1.22  – The transform tools set

Figure 1.22 – The transform tools set

The next tool is the Gizmo handle position toggles set, which is used to define the position of any transform tool Gizmo in the Scene view:

Figure 1.23 – The Gizmo handle position toggles set

Figure 1.23 – The Gizmo handle position toggles set

Then, you can find the Play, Pause, and Step buttons in the center. You can use these buttons in the Game view:

Figure 1.24 – The Play, Pause, and Step buttons

Figure 1.24 – The Play, Pause, and Step buttons

On the right side, let's take a look at the Unity Plastic SCM button first, which allows you to access the Plastic SCM version control and source code management tool in the Unity Editor directly. You can click the cloud button to open the Unity Services window, where you are able to access a lot of cloud services provided by Unity, such as the Cloud Build service, the Analytics service, and the Ads service.

You can also access your Unity account from the Account drop-down menu. There are two other drop-down menus on the right, namely Layers and Layout; you can control which objects in the Scene view appear using the Layers drop-down menu and change or create a new layout of your Unity Editor using the Layout drop-down menu:

Figure 1.25 – The Unity Collaborate and Unity Services buttons and 
the Unity Account, Layers, and Layout dropdowns

Figure 1.25 – The Unity Collaborate and Unity Services buttons and the Unity Account, Layers, and Layout dropdowns

The Hierarchy window

The second area is the Hierarchy window. As you can see in the following screenshot, the Hierarchy window in the Unity Editor displays everything in a Scene; the things in the Scene, such as Main Camera, Directional Light, and the 3D cube, are called GameObjects.

We can also organize all the objects in the game world in the Hierarchy window:

Figure 1.26 – The Hierarchy window

Figure 1.26 – The Hierarchy window

It is very easy to create a new GameObject in a Scene. You only need to right-click on the Hierarchy window, and a menu will pop up where you can select the object you want to create:

Figure 1.27 – Creating a new GameObject

Figure 1.27 – Creating a new GameObject

It is worth noting that Unity uses parent-child hierarchies to organize GameObjects, so you can create one object as a child of another. If you want to create a new GameObject as a child of another GameObject, then you only need to select the parent GameObject first and then right-click to create the child GameObject:

Figure 1.28 – The parent-child hierarchy

Figure 1.28 – The parent-child hierarchy

Another way to create a parent-child hierarchy is to directly drag an existing GameObject onto the parent GameObject in the Hierarchy window:

Figure 1.29 – The parent-child hierarchy

Figure 1.29 – The parent-child hierarchy

As you can see in the preceding screenshot, we dragged the GameObject named Cube onto the GameObject named Child to create a parent-child hierarchy.

Figure 1.30 – Hiding and showing GameObjects

Figure 1.30 – Hiding and showing GameObjects

Another feature of the Hierarchy window is that it allows you to hide and show GameObjects in the Scene view without changing their visibility in the Game view or the final application.

The Scene view and the Game view

The center of the default Unity Editor layout is the Scene view and the Game view, which is the most important window in the Unity Editor. The Scene view is an interactive view of the game world you are creating:

Figure 1.31 – The Scene view

Figure 1.31 – The Scene view

You can use the Scene view to manipulate GameObjects and view them from various angles. Also, there are some useful tools available in the Scene view, such as the Scene Gizmo tool at the upper-right corner of the Scene view:

Figure 1.32 – The Scene Gizmo tool

Figure 1.32 – The Scene Gizmo tool

It shows the current orientation of the Scene view camera and allows you to quickly modify the angle of the view and projection mode.

If you want to modify the settings of the Scene view camera, you can click the Camera button next to the Gizmos button to open the Scene Camera settings window:

Figure 1.33 – The Scene Camera settings

Figure 1.33 – The Scene Camera settings

Here, you can adjust some settings of the Scene view camera, such as Field of View and Camera Speed.

A visual grid is another useful tool that you can use in the Scene view to help you align GameObjects by moving them to the nearest grid location:

Figure 1.34 – Toggle the visibility of the grid

Figure 1.34 – Toggle the visibility of the grid

As you can see in the preceding screenshot, you can also move a GameObject to a grid projected along the X, Y, or Z axes.

The last useful tool in the Scene view that I want to introduce is draw mode used in the Scene:

Figure 1.35 – The draw mode in the Scene

Figure 1.35 – The draw mode in the Scene

This is useful if your project uses the built-in render pipeline of Unity because a different draw mode in the Scene can help you understand and debug the lighting in it.

In the default layout, the Game view also appears in the same area as the Scene view. You can click the Game button to switch to the Game view from the Scene view:

Figure 1.36 – Click the Game button to switch to the Game view

Figure 1.36 – Click the Game button to switch to the Game view

The Game view represents your final published game. The content of the Game view is rendered from the camera(s) in your game. In the Game view, you cannot modify the viewing angle and projection mode at will, as with the Scene view. You need to modify the settings of the camera object to achieve this function:

Figure 1.37 – The Game view

Figure 1.37 – The Game view

You can run your game directly inside the Game view by clicking the Play button on the Toolbar. It's important to note that in Play mode, any changes you make are temporary and will be reset when you exit it; therefore, it is not a good idea to make lots of changes in play mode.

I want to introduce three tools in the Game view, namely Aspect, Maximize On Play, and Stats.

The Aspect drop-down menu is very useful when you develop games for different screens with different aspect ratios. You can select different values to test how your game looks on these screens, and you even can add custom values by clicking the plus button at the bottom of the menu:

Figure 1.38 – The Free Aspect drop-down menu

The second feature is called Maximize On Play, which can maximize the Game view for a full-screen preview when you enter play mode:

Figure 1.39 – The Maximize On Play button

The third feature is called Stats. This feature is useful because it can display the rendering statistics about your game's audio and graphics. Therefore, you can use it for monitoring the performance of your game while in play mode:

Figure 1.40 – The Stats window

In the Scene view, you can view and adjust the game world you are creating. In the Game view, you can see your final game. So, this area is very important in the Editor. Next, let's take a look at the UI area related to a specific GameObject in the Scene.

The Inspector window

If you want to modify the properties of a GameObject or a component on a GameObject, you need to use the Inspector window.

You can select a GameObject in the Scene view or the Hierarchy window, and then you will see the properties and the components of it in the Inspector window:

Figure 1.41 – The Inspector window of a GameObject

You can modify these properties directly in the Inspector window, which also provides some useful tools that can help you modify your GameObjects.

For example, if you want to copy the values of a component on a GameObject, you can right-click on the component, and then a menu will pop up; from there, you can select the Copy Component command:

Figure 1.42 – Copy Component

Not only can the GameObjects in the Scene view be inspected but also the digital assets in the Project window. You can select a digital asset in the Project window, and the Inspector window will display the settings that control how Unity imports and uses the asset at runtime:

Figure 1.43 – The Inspector window of an asset

In this section, we learned how to view and modify the properties of a GameObject and asset through the Inspector window.

The Project window

The final window I will introduce is the Project window. In the Project window, you can find all the digital assets of your project. The Project window works like a file browser, organizing assets files in folders:

Figure 1.44 – The Project window

The Project window is the main way to navigate and find assets in your game. It provides two ways to search assets, by type or label:

Figure 1.45 – Searching assets by type

It is very easy to import external digital assets or create an asset inside the Unity Editor directly. You just need to right-click on the Project window and a menu will pop up where you can create a new asset or import an existing asset:

Figure 1.46 – Creating an asset

I hope you now have a good understanding of the Unity Editor by reading this section. Next, I will introduce what a game engine is and what important features Unity provides as a game engine.

 

Working with different features in Unity

Nowadays, Unity is no longer just a game engine but also a creative tool widely used in various industries. However, Unity still retains its game engine roots, and it remains one of the most popular game engines. To learn how to use Unity to develop games, you must first understand what features Unity provides for game developers as a game engine.

In fact, almost all game engines provide similar functional modules to Unity to game developers. So, the first question is, what exactly is a game engine?

What is a game engine?

The term game engine is widely used in the game industry, but not everyone knows what this term means, especially new game developers. So, I will explain what a game engine is and, at the same time, introduce the corresponding functions in Unity.

A game engine is not just a computer graphics renderer. Of course, rendering is an important function of a game engine, but the process of creating a game is much more complicated than just rendering.

As a game developer, you need to import different types of digital assets, such as 3D models, 2D textures, and audio, and most of these digital assets are not created inside a game engine. Therefore, a game engine should provide the function of managing digital assets. In addition to digital assets, you also need to use scripts to add game logic to guide these assets to perform correct behaviors, such as character interactions.

UI is another integral part of a game, and even some gameplay is based on UI. Therefore, a good game engine should provide an easy-to-use and powerful UI toolkit to develop user interfaces for games.

You can use other software to develop animation files and import them into a game engine, but in order for animation files to be played and controlled correctly in the game, the game engine needs to provide an animation feature.

At the same time, a physical effect is a common function in modern games, so a powerful game engine should provide a physical function so that game developers do not need to implement a physical effect from scratch.

There is no doubt that adding video and audio to your game can make your game livelier and more interesting. With audio especially, suitable background music and some appropriate sound effects can make your game feel completely different. Even if it is just a prototype, background music and sound effects can make the game more complete and more professional. Therefore, although many people often ignore the functions of video and sound when talking about game engines, I don't think that a game engine without video and audio functions is a good one.

As you can see, there are many features in a game engine for game developers to develop their games. A game engine integrates all aspects of creating a game to create a complete game user experience. So, in game development, you will deal with different functions. For example, you may need to properly manage digital assets and create appropriate digital assets for your game engine to optimize performance at runtime, or you may need to know how to use the scripting function provided by the game engine you are using to develop logic for your game.

As one of the most popular game engines, Unity also provides the aforementioned functions. In the following subsection, I will introduce these functions in Unity.

Features in Unity

Like other excellent game engines, Unity also provides many functions for game developers. You will be introduced to these functions in the following sections.

Graphics

The first feature I want to introduce is graphics in Unity. You can use Unity's graphics features to create beautiful, optimized graphics on various platforms:

Figure 1.47 – A Unity HDRP template Scene

A render pipeline performs a series of operations that render the contents of a Scene on a screen. There are three render pipelines available in Unity:

  • The Built-in Render Pipeline, which is the default render pipeline in Unity. You cannot modify this render pipeline.
  • The Universal Render Pipeline (URP), which allows developers to customize and create optimized graphics for different platforms.
  • The High Definition Render Pipeline (HDRP), which focuses on cutting-edge, high-fidelity graphics on high-end platforms.

In addition, you can also create your own render pipeline by using the Scriptable Render Pipeline API in Unity. We will introduce it in detail in Chapter 8, The Scriptable Render Pipeline in Unity.

Scripting

Scripting is another essential feature of Unity. You need scripts to implement the game logic in your games.

The Unity engine is built with native C/C++ internally, but it offers scripting APIs in C#, so you do not have to learn C/C++ to create a game. In the following sections and chapters, you will learn more about the concepts of scripting.

UI

UI is very important for a game, and Unity offers three different UI solutions for game developers:

  • The Immediate Mode Graphical User Interface (IMGUI)
  • The Unity UI (uGUI) package
  • The UI Toolkit

The IMGUI is a relatively old UI solution in Unity, and it is not recommended for building a runtime UI. The UI Toolkit is the latest UI solution; however, it is still missing some features that you can find in the uGUI package and the IMGUI. The uGUI package is a mature UI solution in Unity, which is widely used in the game industry. We will introduce the uGUI package in detail in Chapter 3, Developing UI with the Unity UI System.

Animation

Animation can make your game more vivid. Unity provides a powerful animation feature called Mecanim that allows you to retarget an animation, control the weight of it at runtime, and call events from the animation playback.

We will introduce Unity's animation system in Chapter 4, Creating Animations with the Unity Animation System.

Physics

Physical simulation is an indispensable feature in certain types of games, and some gameplays are even based entirely on physical simulation. There are different physics engine implementations in Unity, and you can select one according to your game needs.

We will introduce Unity's physics engine implementations in Chapter 5, Working with the Unity Physics System.

Video and audio

Good background music, sound effects, and video can make your game stand out. This is a feature that cannot be ignored. Unity provides video and audio features, allowing your game to play videos on different platforms, and supports real-time mixing and full 3D spatial sound effects.

We will discuss video and audio more in Chapter 6, Integrating Audio and Video in a Unity Project.

Assets

You can import your digital asset files into the Unity Editor, such as 3D models and 2D textures. Unity offers an Asset Import Pipeline to process these imported assets. You can also customize the import settings to control how Unity imports and uses the assets at runtime.

We will introduce assets management and serialization in Chapter 10, Serialization System and Assets Management In Unity and Azure.

We've briefly introduced the functions that a game engine needs to provide and the functions provided by Unity. Next, let's introduce .NET/C# and scripting in Unity.

 

.NET/C# and scripting in Unity

Unity is a game engine written in C/C++, but in order to make it easier for game developers to develop games, Unity provides C# (pronounced C-sharp) as a scripting programming language to write game logic in Unity. This is because compared with C/C++, C# is easier to learn. In addition, it is a "managed language," which means that it will automatically manage memory for you – allocate release memory, cover memory leaks, and so on.

In this section, we will introduce .NET/C# and scripting in Unity.

.NET profiles in Unity

The Unity game engine uses Mono, an open source ECMA CLI, C#, and .NET implementation, for scripting. You can follow the development of Unity's fork of Mono on GitHub: https://github.com/Unity-Technologies/mono/tree/unity-master-new-unitychanges.

Unity provides different .NET profiles. If you are using the legacy version of Unity, which is before Unity 2018, you may find that it provides two API compatibility levels in the Player settings panel (Edit | Project Settings | Player | Other Settings), which are .NET 2.0 Subset and .NET 2.0. First of all, if you are using a legacy version of Unity, then I strongly recommend that you update your Unity version. Secondly, both the .NET 2.0 Subset and .NET 2.0 profiles in Unity are closely aligned with the .NET 2.0 profile from Microsoft.

If you are using a modern version of Unity, which is Unity 2019 or later, you will find another two .NET profiles supported by Unity, which are .NET Standard 2.0 and .NET 4.x:

Figure 1.48 – The Api Compatibility Level settings

Note

The name of the .NET Standard 2.0 profile can be a bit misleading because it is not related to the .NET 2.0 and .NET 2.0 Subset profiles from the legacy versions of Unity.

.NET Standard is a formal specification of the .NET APIs that all .NET platforms have to implement. These .NET platforms include .NET Framework, .NET Core, Xamarin, and Mono. You can find the .NET Standard repository on GitHub: https://github.com/dotnet/standard.

On the other hand, the .NET 4.x profile in Unity matches the .NET 4 series (.NET 4.5, .NET 4.6, .NET 4.7, and so on) of profiles from the .NET Framework.

Therefore, it is a good idea to use the .NET Standard 2.0 profile in Unity, and you should choose the .NET 4.x profile only for compatibility reasons.

Scripting backends in Unity

In addition to the .NET profiles, Unity also provides two different scripting backends, which are Mono and IL2CPP (which stands for Intermediate Language To C++):

Figure 1.49 – The Scripting Backend settings

You can change the scripting backend of your project in the same settings panel, which can be found by going to Edit | Project Settings | Player | Other Settings.

The key difference between the two scripting backends is how they compile your Unity scripting API code (C# code):

  • The Mono scripting backend uses Just-in-Time (JIT) compilation and compiles code on demand at runtime. It will compile your Unity scripting API code to regular .NET DLLs. And, as I mentioned in the previous sections, Unity uses an implementation of the standard Mono runtime for scripting that natively supports C#.
  • Alternatively, the IL2CPP scripting backend uses Ahead-of-Time (AOT) compilation and compiles your entire application before it is run. And it not only compiles your Unity scripting API code into .NET DLL but also converts all managed assemblies into standard C++ code. In addition, the runtime of IL2CPP is developed by Unity, which is an alternative to the Mono runtime:

Figure 1.50 – The IL2CPP scripting backend

As shown in Figure 1.50, IL2CPP not only compiles C# code into managed assemblies but also further converts assemblies into C++ code, and then compiles the C++ code into the native binary format.

Clearly, IL2CPP takes more time to compile code compared to Mono, so why do we still need IL2CPP?

Well, first, IL2CPP uses AOT compilation, which takes longer to compile, but when you ship the game for a specific platform, the binary files are fully specified, which means that compared to Mono, code generation is greatly improved.

Second, it is worth noting that IL2CPP is the only scripting backend available when building for iOS and WebGL. In addition to iOS and WebGL, Unity has added support for Android 64-bit in Unity 2018.2 to comply with the Google Play Store policy, which requires that starting from August 1, 2019, your apps published on Google Play need to support 64-bit architectures:

Figure 1.51 – The Android 64-bit ARM architecture is not supported on the Mono scripting backend

And as you can see in the preceding screenshot, the Android 64-bit ARM architecture is not supported on the Mono scripting backend. In this situation, you have to choose the IL2CPP scripting backend.

So, whether we use IL2CPP for better code generation or some specific platforms or architectures, spending more compilation time is still a disadvantage of IL2CPP. So, how should we optimize the compilation time of IL2CPP? I think the following tips will help:

  • Don't delete the previous build folder, and build your project with the IL2CPP scripting backend at the same location as the folder. This is because we can use incremental building, which means the C++ compiler only recompiles files that have changed since the last build.
  • Store your project and target build folder on a Solid-State Drive (SSD). This is because when IL2CPP is selected, the compilation process will convert the IL code into C++ and compile it, which involves a lot of read/write operations. A faster storage device will speed up this process.
  • Disable anti-malware software before building the project. Of course, this depends on your security strategy.

Well, I hope that by reading this section, you now have a general understanding of Unity's scripting system, such as the .NET profiles in Unity, the two scripting backends, and some optimization tips for IL2CPP.

In the next section, you will learn how to set up your development environment and use the widely used Visual Studio to develop games in Unity.

 

Building Unity games with Visual Studio

Before you start writing any code, it is important to choose suitable development tools. Microsoft's Visual Studio is not only a widely used IDE but also the development environment that is installed by default when you install Unity on Windows or macOS:

Figure 1.52 – Visual Studio Installer

While installing Visual Studio, Visual Studio Tools for Unity will also be installed. It is a free extension that provides support for writing and debugging C# in Unity.

If you do not install Visual Studio through the Unity Hub, please make sure you installed this extension. You can check it in the Visual Studio Installer:

Figure 1.53 – Installing Visual Studio Tools for Unity

After installing the Unity Editor and Visual Studio Community 2019, you can check the External Script Editor settings in the Preferences window of the Unity Editor:

Figure 1.54 – The External Script Editor settings

In addition, you can also select other script editors by modifying this setting, such as Visual Studio Code and JetBrains Rider.

Then, we can create a new C# script file named NewBehaviourScript in the Unity Editor and double-click to open it in Visual Studio:

Figure 1.55 – IntelliSense for the Unity APIs

As you can see in the preceding screenshot, there are two built-in methods in the script file by default, namely Start and Update. Visual Studio supports IntelliSense for Unity APIs, so we can write code quickly:

Figure 1.56 – Debugging your code

It is also very easy to debug your code in Visual Studio. In the preceding screenshot, I set a breakpoint inside the Start method and clicked the Attach to Unity button in Visual Studio:

Figure 1.57 – Clicking the Attach to Unity button

In order to run this code, I attach this script to a GameObject in the Scene and click on the Play button in the Unity Editor to run the game in the Game view.

Figure 1.58 – The debugger stopping at the breakpoint

Then, the debugger will stop at the breakpoint, and you can look at the current state of the game.

 

Summary

In this chapter, we started by choosing the Unity release and subscription plan that suits your needs. Then, you learned how to install and manage the Unity Editor by using the Unity Hub and explored the five important areas of the Unity Editor – the Toolbar, the Hierarchy window, the Scene view and the Game view, the Inspector window, and the Project window. You were then introduced to the Unity Editor toolbars and the windows provided by Unity. We also discussed what a game engine is and explored the different features provided by Unity for developers to develop games. We then introduced the .NET profiles in Unity and the scripting backends offered by Unity; you should now know the difference between the Mono scripting backend and the IL2CPP scripting backend. Finally, we demonstrated how to set up Visual Studio for Unity Editor to write code.

In the next chapter, we will start with a detailed introduction to the basic concepts of scripting in Unity, such as GameObjects, components, and some special, important components such as Transform. We will also introduce you to the life cycle of a script instance. Then, we will discuss how to create objects from scripts and how to access GameObjects or components through C# code. Some best practices for scripting in Unity will also be introduced. Finally, we will introduce packages and the Package Manager in Unity.

About the Author
  • Jiadong Chen

    Jiadong Chen is one of 3,000 Microsoft Most Valuable Professional (MVP) award winners internationally, recognized by Microsoft as one of the technology industry’s best and brightest six years in a row, and is currently working as a Senior Software Developer at Company-X, based in Hamilton, New Zealand. He is interested in Microsoft Azure cloud, Unity and XR development, and .NET/C#. He is a Microsoft Certified Azure Solutions Architect Expert, Microsoft Certified Azure Developer, Microsoft Certified Azure AI Engineer, Microsoft Certified Trainer. He is also a member of the .NET Foundation. Before joining Company-X, Jiadong worked for Company-U (Unity), the creator of the world’s most widely-used real-time 3D development platform, as a Field Engineer.

    Browse publications by this author
Game Development with Unity for .NET Developers
Unlock this book and the full library FREE for 7 days
Start now