Unity keyboard shortcuts

3D Game Design with Unity

This page provides examples of C# syntax and some basic sample scripts to help you get started with scripting in Unity or if you forget the syntax to common operations or statements in the C # (C Sharp) programming language.

C# Data Types

The table below shows the data types available in the C# language.

Type Description
int The integer data type stores positive or negative whole numbers eg. 5
float The float data type stores floating point numbers (numbers with decimal places). The float data type is the default number type in Unity eg. 5.25
double The double data type stores floating point numbers but can hold larger size numbers than floats. It is not the default number type in Unity though.
bool The bool (short for Boolean) data type stores true or false values only eg. true
char The char data type stores a single character such as a letter, number, space or special character (eg. a, 1, !).  A char value is written in single quotes eg. ‘a’.
string The string data type stores letters, numbers and other characters in the form of words or sentences. A string value is written inside double quotes eg. “Hello World”.

Basic template script

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. This code should not be deleted but may be added to (eg. to gain access to functions for working 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 must start with an uppercase letter. The script name (without the ‘.cs’ part) must match the class name. 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

Variables

To create a variable it must first be given a name and a type. Variable declaration uses the following syntax:

<variable type> <variable name>;

Variables should be given meaningful names. Variable names should never contain spaces. To declare a variable that is of the integer data type and is called myNumber, you would write the following:

int myNumber;

You can also assign a value to a variable during its declaration like this.

int myNumber = 5;

Or you can assign a value on another line after the variable has been declared like this:

myNumber = 5;

To declare a string variable, you would write something like this:

string message;

And you can also assign the value during declaration like this:

string message = "Hello World";

These are just a few examples of how to create variables in C#. Remember that strings are contained inside double quotes and chars are contained inside single quotes. Integers, floats, doubles, and boolean values are not placed inside quotes.

Variable scope

The scope of a variable dictates where it can be used. As mentioned earlier, classes and methods use opening and closing brackets and everything inside those brackets is called a ‘block’.

Variables can only be used within the block that they were created in. If a variable is created inside a class, it can only be used inside that class. If a variable is created inside a method (or function), it can only be used inside that method. For example, if you create a variable inside the Start method, it can’t be used inside the Update method because they are two different blocks.

However, if a variable is created in a class but outside of all of the methods on that class, it will be available in all of the methods in that class because those methods are in the same ‘block’ that the variable is in.

Public and private

In code, you might see the keywords public or private. These are known as access modifiers. Private variables can only be used inside the file that they were created in. This means that other scripts or code editors cannot see or modify these variables.

However, public variables are visible to other scripts and can even be seen and modified inside the Unity editor (Inspector). This makes it really easy to change values for variables right in the Unity editor without having to change the values in your code editor such as MonoDevelop.

To make a public or private variable, just add the private or public keyword before the variable type and name during declaration, for example:

public int myNumber;

Operators

Operators are symbols that are used to perform operations on data. The range of different operations you can perform can usually be placed in these four categories:

  • Arithmetic operators

  • Assignment operators

  • Equality operators

  • Logical operators

You will see how these operators can be used for conditional statements after reading further on.

Arithmetic operators

Arithmetic operators are used for performing standard math operations on variables and are usually only used on number variables (although they can be used for other things too).

Brackets can also be used for more complex math operations eg. 5 + (10 * (6 / 3) / 2);

The assignment operators follow standard mathematic order of operations. That means that the math works from left to right. Parenthesis are done first, multiplication and division comes second, and then addition and subtraction come third.

Assignment operators

Assignment operators are used to assign a value to a variable. The most frequently used assignment operator is the equals (=) sign. There are other operators as well that are used to combine multiple operations into one. The syntax of a standard variable assignment looks like this:

<variable name> <assignment operator> <value>;

For example: x = 5;

The table below shows the different assignment operators available in C#.

Operator Name / description
+ Addition – this operator is used to add two numbers together. It can also be used to concatenate (join) two strings together.
Subtraction – this operator is used to subtract one number from another.
* Multiplication – this operator is used to multiply two numbers together.
/ Division – this operator is used to divide one number by another.
% Modulus – this operator is used to divide one number by another but instead of returning the result, it returns the remainder of the division. Eg. 5%2 would return a result of 1.
Operator Description
= The equals sign is used to assign the value on the right side of the equals sign to the variable on the left side of the equals sign.
+= , -= , *= and /= These assignment operators are also used to perform arithmetic operations and assign the result to the variable eg. x *= 5 is the same as saying x = x * 5.
++ and — These assignment operators are called increment and decrement operators and are used to increase or decrease the value of a variable by 5. For example, x++ is the same as saying x = x + 1.

Equality operators

Equality operators are used to compare two values. The result of using an equality operator can either be true or false. The only type of variable that can store the result of an equality operator is a Boolean. The table below describes the equality operators used in C#.

Operator Description
== This operator is used to check if two values are equal eg. x == 5 would return true if x had a value of 5.
> and < The ‘greater than’ and ‘less than’ operators are used to check if values are greater than or less than another value. For example, x > 5 (if the value of x was 3 than it would return false).
>= and <= The ‘greater than or equal to’ and ‘less than or equal to’ operators are similar to the ‘greater than’ and ‘less than’ operators. For examples, 5>=5 would return true because 5 is equal to 5, and 6<=10 would return true because 6 is less than 10.
!= The ‘not equal’ operator is used to check if two values are not the same as each other. For example, x != 10 would return true if the value of x was 9 because 9 is not equal to 10. However, y != 5 would return false if the value of y was 5.

Logical operators

Logical operators are used for complex conditions. The table below describes each logical operator.

Operator Description
&& This is known as the AND operator and is used to check if both values are true in a complex condition.
|| The is known as the OR operator and is used to check if at least one of the values is true when two values are compared. It will return true if either one or both values are true.
! This is known as the NOT operator and will return the opposite of a Boolean value. For example !true; would return false and !false; would return true.

Conditional statements

Conditional statements are used so that your program can make decisions. When your program has a range of conditions, you can build powerful algorithms. A basic conditional statement is the if statement.

if statements

The most basic type of conditional statement is the if statement. The if statement basically works like this: if something is true, then do this. The basic syntax looks like this:

if( <condition>)
{
// do something
}

The condition goes inside the ( and ) brackets. The action that will occur (if the condition evaluates to true) goes inside the { and } brackets. For example, to say the message “Hello World” only if the value of x is greater than 10, you would use the following code:

if(x>10)
{
 print("Hello World");
}

In the code above, the condition is to check whether x is greater than 10. As an example, if the value of x was 11, then the message “Hello world” would be displayed. If the value of x was 9, then nothing would happen. If the value x was exactly 10, nothing would happen because the value of x needs to be greater than 10 for the message to be displayed.

if/else statement

Regular if statements are easy to use. However, they don’t specify what the program should do if the condition evaluates to false. if/else statements allow you to specify what action will occur when a condition evaluates to true and also what will occur if the condition evaluates to false. This is known as a binary selection structure.

The if/else statement basically reads as “if something is true, then do this, otherwise do this other thing”. The syntax looks like this:

if(<condition>)
{
// do something
}

else
{
// do something else
}

Here is an example of a basic if/else statement that will display a message based on someone’s age stored in an ‘age’ variable.

if(age>=18)
{
 print("You are old enough to vote");
}
else
{
 print("You are not old enough to vote");
}

if/else if statement

The limitation of the if/else statement is that it only allows two possible paths. What if you want your program to be able to go down many different paths? What if you have many different conditions you want to check? That is where the if/else if statement comes in.

The if/else if statement provides more options than the if/else statement. It is set up in the same way but it has more than one condition. The else part is optional in an if/else if statement.

Here is some sample code for the if/else if statement:

if(age>=18)
{
 print("You are old enough to vote");
}
else if(age==17)
{
 print("You can vote after your next birthday");
}
else
{
 print("You are not old enough to vote");
}

Loops (iteration)

There are two main types of loops you can use in C# to repeat sections of code. These are called the while loop and for loop.

while loop

The while loop is the easiest type of loop to use for repetition of code. The basic syntax is as follows:

while(<condition>)
{
// do something
}

It looks very similar to an if statement. However, an if statement only runs the code it contains once. A while loop will run the code that it contains over and over again until the specified condition evaluates to false. Any code inside the { and } brackets will run inside the loop.

Here is an example of a while loop in the C# language:

int count = 0;
 
while(count <10)
{
 count++;
}
print(count);

In the example above, the count variable is initially set to 0. The loop will check if the count variable is less than 10. If it is not less than 10, it will add 1 to the count variable. This will keep repeating until the condition evaluates to false when the count variable’s value is no longer less than 10. When this occurs, the loop will end and the value of the count variable will be displayed (on the last line of the code which is outside of the loop).

It is important that a condition be specified that will allow the loop to end, otherwise the loop will never end! This is known as an infinite loop.

for loop

The for loop is a little more complex than the while loop but at its simplest level it is very easy to set up. The syntax looks like this:

for(<initialise counter>;<condition>;<increment the counter>)
{
// do something
}

Semi-colons separate three important components of the for loop inside the ( and ) brackets. The first part is where a counter is initialised, for example int i=0. The second part is where the condition is specified, for example i<10. The third part is how much to increment the counter by each time the loop runs (each iteration), for example i++ would increment the counter by 1.

for loops are great for using as counters to repeat a section of code a certain amount of times. They are also great for repeating operations on each item in an array (looping through an array) or each character in a string. Below is an example of a for loop.

for(int i=0; i <10; i++)
{
 print(i);
 // the value of i will be displayed for each iteration of the loop
}

Methods

A method, also known as a function, is a module of code that a programmer can create and then call on later on in the program. Many methods already exist in programming languages such as C# but the programmer also has the ability to make their own. A method will usually perform a single task. Many methods can work together to achieve a goal.

In Unity, the Start method contains all of the code that will run for an object when a scene begins. The Update method contains all of the code that runs every single frame of the scene.

This is the basic syntax of a method:

<return type> <name>(<parameters>)
{
// code that runs inside the method goes here
}

Methods should have descriptive names (they should represent an action and are usually in the form of a verb). Spaces cannot be used in method names and you should always avoid the use of special characters eg. $%^!@. The method name itself should also not contain brackets because brackets are used for parameters. When you create a new method, the method name should be unique and not already exist in the language (it should not be a reserved word that is used for a statement or method).

Creating methods

Let’s break up the method into its different components and look at each component…

What is a return type?

Methods are able to return a variable back to the code that called it known as the return type. If a method returns an integer value then the return type is an int and if a method returns a true or false value then the return type is a bool. Even if the method doesn’t return any value, it still has a return type. If the method doesn’t return a value, then its return type is void (which means nothing). You might notice that the Start and Update functions have a return type of void.

What are parameters?

In the same way that methods can pass a variable back to the code that called it, the calling code can pass variables into the method. These variables are known as parameters. The variables that are passed into the method are identified in the parameter list part of the method (inside the brackets). When you specify a parameter you must specify the variable type and the name. If there are no parameters, then the brackets are left empty.

Below is an example of a method in C# for a game in Unity that is used to apply damage to a player’s health. There are two parameters in this method (separated by commas). The parameters in this method are damageAmount and health. Notice that the return type is int.

int applyDamage(int damageAmount, int health)
{
 return health - damageAmount;
}

The above method is a simple example. In an actual game, the player’s health could instead be stored in a variable inside a script so it wouldn’t need to be read into a method. However, the example above shows the structure of methods.

Using methods

Once you have created a method the next thing to do is use it. Using a method is known as calling or invoking a method. To call a method that was named myMethod, you would write:

myMethod();

If the method contained a parameter (eg. the value 10), it would be called like this:

myMethod(10);

The below example shows how to call a method and pass a variable into the method. You do not need to write int inside the brackets where the function is called.

int x = 10;
myMethod(x);

When you call a method you do not need to provide the variable type with the variable that is being passed into the method. If the method myMethod() in the example code above returns a value, then it should be stored in a variable, for example:

int result = myMethod(x);

Here is another example of the applyDamage() method:

using UnityEngine;
using System.Collections;
 
public class hitFromLaserScript: MonoBehaviour {
 
 void Start()
 {
 int x = applyDamage(5, 100);
 print ("Player health: " + x);
 
 }
 
 int applyDamage(int damageAmount, int health)
 {
 return health - damageAmount;
 }
 
}

Input

In Unity, you can set up your game to detect specific keypresses and then react to those keypresses. However, there is a better way of setting up input using Unity’s built-in Input Manager.

Input Manager

Setting up your game to detect specific keypresses doesn’t allow players to remap the game input controls to suit their preferences. However, if you use the Input Manager you can allow the player to map the controls to their own liking or use the defaults (eg. the W, A, S and D keys).

You can set up controls for each of the different axes in the Input Manager by clicking Edit > Project Settings > Input. Then you can write a script using the GetAxis() method to detect key presses.

Below is some sample code that will display horizontal and vertical movement in the console when the W, A, S and D keys (or arrow keys) are pressed. Simply place this code inside the Update() method in a script that is attached to an object inside your game’s scene (eg. the Main Camera object).

float horizontalValue = Input.GetAxis("Horizontal");
float verticalValue = Input.GetAxis("Vertical");
 
if (horizontalValue != 0)
{
 print("Horizontal movement: " + horizontalValue);
}
 
if(verticalValue != 0)
{
 print("Vertical movement: " + verticalValue);
}

Save the script and then run the scene. Check the output in the console after pressing the W, A, S and D keys and the arrow keys.

Try out the code above and see what happens when you press the W, A, S and D keys or arrows keys on your keyboard. Also, did you notice how the sentences and values are combined in the print statements above? This is an example of concatenation (where strings are joined together).

Specific key input

Although it is generally a good idea to use the Input Manager for key input detection, it may sometimes be necessary to check whether a specific key has been pressed by the user. To do this, you can use the GetKey() method. This method will read a keycode which corresponds to a specific key on the keyboard. It will then return either a true or false value depending on whether the key is pressed or not.

As an example, to check if the A key is being pressed, you can use the following code. Just place this code inside the Update() method in a script that is attached to an object inside your game’s scene (eg. the Main Camera object).

bool isKeyDown = Input.GetKey(KeyCode.A);

Tip: In MonoDevelop, if you are not sure what keycode corresponds to a key, you can begin typing in the name of the KeyCode object followed by a period. A popup menu should appear, showing you all of the possible choices. This automatic popup feature in MonoDevelop can be used for many other objects/methods too and is pretty handy.

You can use a simple if statement to specify an action to occur when a keypress is detected. For example, the following code will output a message to the console saying that the ‘A’ key has been pressed when it is detected that the ‘A’ key has been pressed.

if(Input.GetKey(KeyCode.A))
{
 print("You pressed the 'A' key.");
}

Save the script and then run the scene. Check the output in the console after pressing the ‘A’ key.

Mouse input

In addition to detecting keypresses, you can also add code to your Unity game that can be used to detect mouse button clicks and mouse movement.

Mouse button clicks

To detect mouse button clicks, you use the GetMouseButtonDown() method which takes an integer value (between 0 and 2) to specify which mouse button you want to check. 0 is for the left button, 1 is for the right button, and 2 is for the middle button. The method will return a Boolean value indicating whether the specified mouse button has been pressed when using code like the example shown below.

bool isLeftButtonDown = Input.GetMouseButtonDown(0);
bool isRightButtonDown = Input.GetMouseButtonDown(1);
bool isMiddleButtonDown = Input.GetMouseButtonDown(2);

This code will display a message if the left mouse button is pressed:

if(Input.GetMouseButtonDown(0))
{
 print("The left mouse button was pressed");
}

Save the script and then run the scene. Check the output in the console when you click the left mouse button.

Mouse movement

Mouse movement is measured by reading the amount that the mouse has moved since the last frame, across the X and Y axes on screen.

The sample code below will read the mouse movement and display the value in the console. Place this code inside the Update() method in a script that is attached to an object inside your game’s scene (eg. the Main Camera object).

float mouseXValue = Input.GetAxis("Mouse X");
float mouseYValue = Input.GetAxis("Mouse Y");
 
if(mouseXValue != 0)
{
 print("Mouse X movement: " + mouseXValue);
{
 
if(mouseYValue != 0)
{
 print("Mouse Y movement: " + mouseYValue);
{

Save the script and then run the scene. Check the output in the console when you move the mouse around the screen.