Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Unity 2020 By Example

You're reading from   Unity 2020 By Example A project-based guide to building 2D, 3D, augmented reality, and virtual reality games from scratch

Arrow left icon
Product type Paperback
Published in Sep 2020
Publisher Packt
ISBN-13 9781800203389
Length 676 pages
Edition 3rd Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Robert Wells Robert Wells
Author Profile Icon Robert Wells
Robert Wells
Arrow right icon
View More author details
Toc

Table of Contents (16) Chapters Close

Preface 1. Chapter 1: Exploring the Fundamentals of Unity 2. Chapter 2: Creating a Collection Game FREE CHAPTER 3. Chapter 3: Creating a Space Shooter 4. Chapter 4: Continuing the Space Shooter Game 5. Chapter 5: Creating a 2D Adventure Game 6. Chapter 6: Continuing the 2D Adventure 7. Chapter 7: Completing the 2D Adventure 8. Chapter 8: Creating Artificial Intelligence 9. Chapter 9: Continuing with Intelligent Enemies 10. Chapter 10: Evolving AI Using ML-Agents 11. Chapter 11: Entering Virtual Reality 12. Chapter 12: Completing the VR Game 13. Chapter 13: Creating an Augmented Reality Game Using AR Foundation 14. Chapter 14: Completing the AR Game with the Universal Render Pipeline 15. Other Books You May Enjoy

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.

You have been reading a chapter from
Unity 2020 By Example - Third Edition
Published in: Sep 2020
Publisher: Packt
ISBN-13: 9781800203389
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image