Introduction to scripts in Unity
2D Game Design with Unity
🕑 This lesson will take about 20 minutes
This lesson provides an introduction to setting up and writing code for 2D games in Unity. The programming language used in this course is the C# programming language. Code written to control a game is stored in files called scripts. Each script contains C# code and the filenames end in the “.cs” filename extension. You will need a code editor such as Visual Studio (there is an option to install this when you install Unity) to write your code in.
When creating a new script (by clicking Assets > Create > C# Script from the top menu), it is important to immediately give the script a unique name. The name must start with an uppercase letter and not contain any spaces (eg. PlayerMovement would be a suitable name for a script responsible for controlling the movement of a GameObject representing the player). Scripts contain a class with a unique name - this class name needs to match the name of the script (this will be covered more in the video below).
Each new script contains these sections of code to get started:
The top of the code includes ‘using’ statements. These should not be deleted. They tell Unity which packages you need access to in the script (packages contain existing code that you can use such as functions for working with physics or collision detection. You can also include additional packages if needed such as packages for working with the user interface or level management).
The next section is the class - this is where you create all your variables and methods/functions that belong to the script. The class name must always match the name of the script.
Start() method - this is where you place code that needs to run first and just be called once when the script is executed (eg. to initialise things in your scene)
Update() method - this is where you place code that needs to run repeatedly during the game (eg. checking which keys are pressed, moving the player, etc). This method is called once per frame during the game.
Other methods can be placed inside the class as well such as specific methods for collision detection.
We’ll get started by adding collision detection so that our player object (or character) can collect points when colliding with coins in the game. You’ll learn how to set up 2D collision detection, increase a score variable, display messages in the console to test your code, and how to destroy objects (or make objects disappear) in a scene using code.
The video below demonstrates how to create a script and explains the different sections of a C# script for Unity.
Is YouTube blocked at school? Watch on Google Drive.
Next lesson: Player Movement