Scripting in Unity

3D Game Design with Unity

🕑 This lesson will take about 17 minutes

In this lesson, you will learn how to start scripting in Unity using the C# language. Scripts are what make your game interactive and where you implement the gameplay - scripts contain code written in the C# programming language to control different aspects of your game. In addition to the videos on coding, make sure you also check out the C# Script Reference page where you can find explanations of different concepts and example code.

Is YouTube blocked at school? Watch on Google Drive.

Every script in Unity has a few required components that you need to include. This template script contains the basic components that every script needs to begin with when using C# scripts in Unity.

This script is made up of three sections:

  • The using section

  • The class declaration section

  • The class contents

The using section

The section of the code lists the libraries that the script will be using. Don’t delete any code from here. You might need to add code later to use different functions in your code (eg. to work with the user interface or level management).

The class declaration section

All scripts contain a class that is named after the actual script. For example, if the script file is called CharacterMovement.cs then the class will be called CharacterMovement. Note that script file names and class names must not contain any spaces and they must begin with an uppercase letter. The first line of this section (the class declaration) doesn’t really get changed much so it should be left alone. All of the code that exists between the opening { and closing } brackets is a part of this class. All of your code will go between these opening and closing brackets.

The class contents

The code placed in between the opening and closing brackets of the class is what makes up the script. All of your code goes here. By default, a script will have two methods inside the class, the Start method and the Update method.

Any code that is placed inside the Start method will run when the scene that it is attached to first starts. Any code that is placed inside the Update method will run every single time the game updates which is usually about 60 times a second but this will depend on the computer being used.

Note that statements in C# have a semi-colon (;) at the end of the line. Leaving the semi-colon out can cause errors.

Comments

The // characters are used to add comments to your code. Any text on a line after the two forward slashes will not be treated as code. Comments are useful as they contain notes about what is happening in the code and can help others understand the algorithm.

Here is an example of a comment:

// This is a comment