Book Image

Unity 2020 By Example - Third Edition

By : Robert Wells
Book Image

Unity 2020 By Example - Third Edition

By: Robert Wells

Overview of this book

The Unity game engine, used by millions of developers around the world, is popular thanks to its features that enable you to create games and 3D apps for desktop and mobile platforms in no time. With Unity 2020, this state-of-the-art game engine introduces enhancements in Unity tooling, editor, and workflow, among many other additions. The third edition of this Unity book is updated to the new features in Unity 2020 and modern game development practices. Once you’ve quickly got to grips with the fundamentals of Unity game development, you’ll create a collection, a twin-stick shooter, and a 2D adventure game. You’ll then explore advanced topics such as machine learning, virtual reality, and augmented reality by building complete projects using the latest game tool kit. As you implement concepts in practice, this book will ensure that you come away with a clear understanding of Unity game development. By the end of the book, you'll have a firm foundation in Unity development using C#, which can be applied to other engines and programming languages. You'll also be able to create several real-world projects to add to your professional game development portfolio.
Table of Contents (16 chapters)

Scripting in Unity

Defining game logic, rules, and behavior often requires scripting. Specifically, to transform a static scene with objects into an environment that does something interesting, a developer needs to code behaviors. It requires the developer to define how things should act and react under specific conditions. The coin collection game is no exception to this. In particular, it requires three main features:

  1. To know when the player collects a coin
  2. To keep track of how many coins are collected during gameplay
  3. To determine whether a timer has expired

Now we have an understanding of the requirements, it's time to create our first script!

Creating a script

There's no default out-of-the-box functionality included with Unity to handle the custom logic we require, so we must write some code to achieve it. Unity's programming language of choice is C#. Previous versions had support for UnityScript (a language similar to JavaScript), but this has been officially deprecated, and you can no longer create new UnityScript files. For this reason, this book will use C#. We'll start coding the three features in sequence. To create a new script file, do the following:

  1. Right-click on an empty area in the Project panel.
  2. From the context menu, choose Create | C# Script. Alternatively, you can navigate to Assets | Create | C# Script from the application menu:
Figure 2.11 – Creating a new C# script

Figure 2.11 – Creating a new C# script

Once the file is created, assign a descriptive name to it. I'll call it Coin.cs. By default, each script file represents a single, discrete class with a name matching the filename. Hence, the Coin.cs file encodes the Coin class. The Coin class will encapsulate the behavior of a Coin object and will, eventually, be attached to the Coin object in the scene. However, at the moment, our Coin class doesn't do anything, as we'll see shortly.

Understanding the coin script

Double-click on the Coin.cs file in the Project panel to open it in Visual Studio (VS 2019 8.4 for Mac) a third-party IDE that ships with Unity. This program lets you edit and write code for your games. Once opened in Visual Studio, the source file will appear, as shown in Code Sample 2.1:

using UnityEngine;
using System.Collections;
public class Coin : MonoBehaviour
{
   // Use this for initialization
   void Start ()
   {
   }
  
   // Update is called once per frame
   Void Update ()
   {
   }
}

Downloading the example code

Remember, you can download the example code files for this book from GitHub with the link provided in the Technical requirements section.

By default, all newly created classes derive from MonoBehavior, which defines a common set of functionality shared by all components. The Coin class features two autogenerated functions: Start and Update. These functions are invoked automatically by Unity. Start is called once (and only once) when the GameObject, to which the script is attached, is created in the Scene, and Update is called once per frame. Start is useful for initialization code and Update is useful for adding behavior over time, such as motion.

Important note

There are other functions that are called before the Start function. We will examine the Unity event execution order in more detail later in the book as it is an important concept to understand. However, for a sneak peek at the execution order, see Unity's online documentation: https://docs.unity3d.com/Manual/ExecutionOrder.html.

The script is not yet attached to our object, therefore the functions would not be called if we were to play the game now. As you'll see shortly, this is easily remedied.

Running the script

Before the script is run, it needs to be attached to the Coin object in the Scene. To do this, drag and drop the Coin.cs script file from the Project panel to the Coin object. When you do this, a new Coin component is added to the object, as shown in Figure 2.12:

Figure 2.12 – Attaching a script file to an object

Figure 2.12 – Attaching a script file to an object

When a script is attached to an object, it exists on the object as a component and is instantiated with the object. A script file can usually be added to multiple objects and even to the same object multiple times. Each component represents a separate and unique instantiation of the class. When a script is attached in this way, Unity automatically invokes its events, such as Start and Update. You can confirm that your script is working normally by including a Debug.Log statement in the Start function:

using UnityEngine;
using System.Collections;
public class Coin : MonoBehaviour
{
   // Use this for initialization 
   void Start () 
   {
      Debug.Log ("Object Created");
   }
   // Update is called once per frame 
   void Update () 
   {
   }
}

If you now press play (Ctrl + P) on the toolbar to run your game, you will see the message Object Created printed to the Console window—once for each instantiation of the class:

Figure 2.13 – Printing messages to the Console window

Figure 2.13 – Printing messages to the Console window

Good work! We've now created a basic script for the Coin class and attached it to the coin. Next, let's update our Coin.cs file to keep track of coins as they are collected.