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:
- To know when the player collects a coin
- To keep track of how many coins are collected during gameplay
- 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:
- Right-click on an empty area in the Project panel.
- From the context menu, choose Create | C# Script. Alternatively, you can navigate to Assets | Create | C# Script from the application menu:
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:
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:
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.