Scripting in Unity with C#

In this tutorial we will look at how to start scripting in Unity using the C# language. Scripts are what are needed to make your game interactive. In addition to the videos on scripting, make sure you also check out the C# Script Reference page where you can find examples of scripting and sample code.

Basic template script

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.

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

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. This is usually left as it is and not changed most of the time.

The class declaration section

All scripts contain a class that is named after the actual script. For example, if the script file is called characterMove.cs then the class will be called characterMove. Note that script file names and class names should not contain any spaces. 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 an can help others understand the algorithm.

Here is an example of a comment:

// This is a comment

Now check out the next tutorial: Data Types and Variables in C#.