Introduction to Unity Scripting – Part 1

Scripting is an essential part of making even the simplest of games. These small collections of code work together to do all sorts of things. By Eric Van de Kerckhove.

Leave a rating/review
Download materials
Save for later

Scripting is an essential part of making even the simplest of games. These small collections of code work together to do all sorts of things: From moving a character around the screen to keeping track of your inventory. Game developers write scripts in Unity in C#, a powerful object-oriented programming language developed by Microsoft around the year 2000. It has since grown to be one of the most popular programming languages out there. The Unity team chose C# as Unity’s main programming language because it’s well documented, easy to learn and flexible.

Unity has a well-documented API at its core that scripts can communicate with. In this tutorial, you’ll be creating a simple game — starting with a few models, while learning how to use the most important parts of the Unity API. You’ll learn how to create C# scripts that:

  • Create variables that can be changed in the editor.
  • Detect player input and react to it.
  • Use physics to create interactions.
  • Change values over time in several different ways.

Before starting off, make sure you meet the following requirements:

With that out the way, you’re ready to discover the Unity API by making a simple game!

Getting Started

Download the materials for the project using the Download Materials button at the top or bottom of this tutorial, unzip it somewhere and open the starter project inside Unity.

To start off, direct your attention to the Project window and unfold the RW folder. This project comes with a bunch of pre-made assets that you’ll be using to blow life into the game with scripting:

To focus on the scripting, here’s the included asset folders and their content:

  • Materials: A single material that’s shared between all models for optimal performance.
  • Models: Some models that range from a small smoke puff to the big ground model .
  • Music: The background music for the game. The song is Flying Kerfuffle by Kevin MacLeod.
  • Prefabs: A bunch of pre-made prefabs to make it easier to make changes to GameObjects already present in the scenes.
  • Scenes: A Game and a Title scene.
  • Scripts: Empty! Here’s where you’ll place the scripts you’ll be creating.
  • Sounds: A few 8-bit sound effects created using bfxr.
  • Sprites: There’s a single sprite sheet in here for some small UI elements.
  • Textures: A single texture that’s used by the shared material.

Now, open up the Game scene under RW/Scenes if it isn’t opened yet and take a look around in the Scene view.

There are some floating islands with windmills, bridges and a small rail line with a blue hay machine sitting on top. Now, take a glance at the Hierarchy:

Here’s a quick overview of the GameObjects:

  • Music: An audio source playing a happy tune on loop.
  • Main Camera: The camera that points down at the scene to give a good overview.
  • Directional Light: A single light source that emulates a sun.
  • Scenery: This GameObjects hold the ground and the windmills.
  • Hay Machine: This is the blue machine sitting on the rails. It’s made out of a few GameObjects to make it easy to customize later on.

Next, click the play button at the top of the editor and take a look at the Game view to see what happens.

The only signs of life at the moment are the smoke particles flying up from the hay machine. It won’t win any game of the year awards any time soon, but it’s a good foundation to build on. :]

Click the play button again to stop testing the “game”.

Now that you’re familiar with the project, it’s time to get scripting!

Your First Script

Creating new scripts in Unity is quite easy. Right-click the RW/Scripts folder, select Create ► C# Script and name the script Rotate.

Unity now creates and immediately compiles a bare bones MonoBehaviour script.

While the script won’t do anything yet, you can already use it as a component by attaching it to a GameObject. In this case, the Rotate script will turn the wheels of all windmills around.

Components are instances of scripts, meaning that you can add as many of the same component to any GameObject as you like. Any changes made to the script will reflect in all its components.

Unfold Scenery in the Hierarchy to reveal its children. Open Windmill in the prefab editor by clicking the arrow next to its name.

Note: Unity recently updated their prefab system. For an in-depth look at the new system, check out this great tutorial!

Select Wheel, it’s the grandchild of Windmill. Now, click the Add Component button at the bottom of the Inspector, start typing “rotate” until the Rotate component appears in the list and select it.

This will add the Rotate component to the wheels of all windmills.

To edit the script, you’ll need to open it in a code editor like Visual Studio. There are a few ways of opening a script, but the easiest ways are by either finding the source file in the Project window and double-clicking it. Double-clicking the Script field of any component also works:

Use any of the methods above to open the Rotate script in your default code editor. Here’s what that looks like in Visual Studio:

The script itself is a single class that derives from MonoBehaviour, Unity’s base class that all scripts should derive from if they need to be used as components.

MonoBehaviour is part of the UnityEngine namespace and implements a few public methods but — more importantly — a huge list of event functions.

Note: Functions are another name for methods, all of these are subroutines. In OOP languages such as C# you should use the term method, but Unity has chosen to go with function instead when describing most of its built-in methods.

Unity adds the Start and Update methods by default to all new scripts. These are actually event functions, they get called when a specific action triggers them. Here’s a handful of the most common event functions and when they get called:

  • Start: First time the component is initialized.
  • Update: Every frame.
  • OnEnable: When the component is (re)enabled.
  • OnDestroy: When the component is destroyed.

You’ll be using a lot more of them over the course of this tutorial as they’re an essential part of scripting. You can check out the full list of event functions in Unity’s documentation.

Add the following line inside of Update:

transform.Rotate(0, 50 * Time.deltaTime , 0);

This single line that does a constant rotation on the Y-axis over time already shows some of the abilities of the Unity API:

  • transform is an inherited property of MonoBehaviour. It returns the Transform of the GameObject the component gets attached to. The Transform class allows you to read and change a GameObject’s position, rotation and scale.
  • Rotate is one of the public methods of the Transform class, one of its signatures is used here to pass on a rotation in degrees to the X, Y and Z axes respectively.
  • The value passed for the Y-axis is 50 * Time.deltaTime. Time.deltaTime is part of the UnityEngine namespace and returns the time in seconds between the last and the current frame. This value can change values over time independent of framerate. In essence, this prevents stuff from going slow motion on slow machines and into hyper mode on faster ones. Multiplying the value from Time.deltaTime with 50 means that you want the value to increase by 50 per second. In this case that’s a rotation of 50 degrees on the Y-axis over the time span of a second.

As this line has been added to Update, it gets executed every frame while the component is enabled. This results in a smooth, constant rotation.

Note: The Unity editor uses Euler angles to modify the rotation of GameObjects — these are the familiar X, Y and Z axes. The Unity engine actually uses Quaternions internally that consist of X, Y, Z and W values. These values are very hard to interpret and aren’t meant to be used directly. To read more about the difference, take a look at Unity’s documentation on the subject.

Save this script and return to the editor.

You’ll the notice the editor will be unresponsive for a very short time while it’s compiling. You can check when this compilation is happening by looking at the bottom right corner of the editor, there will be a small animated icon:

If you haven’t exited the Prefab editing mode, do so now by clicking the left pointing arrow next to the Windmill prefab in the Hierarchy. You’ll be prompted to Save or Discard your changes. Click Save.

Now, play the scene. You’ll notice the windmill wheels are now slowly turning around, so relaxing.

Now, let’s say you want to tweak how fast the wheels are turning, or you want to add the Rotate component to another GameObject that needs to turn on a different axis. Wouldn’t it be nice if you could change those values in the editor?

That’s where variables come in!