Show Menu

Unity 2D Basics Cheat Sheet by

Unity editor and scripting basics
api     c-     scripting     editor     unity     gamedev

Editor's Interface

Scene view
Build the game world, interact with game objects
Game view
Preview and play game (pressing Play in Toolbar)
Show and modify game objects' compon­ents' properties
Game objects in game
Assets available
Bar with buttons at the top. Contains transform tools, play controls, layers and layout
Files (scripts, textures, models, prefabs)
Contains debug logs and errors
Tags, Layers, Sorting Layers
Open from Edit > Project Settings > Tags and Layers. Tags are identi­fiers for Game Objects. Game Objects can belong to Layers. Objects in last Layers are rendered above the others. Sprite­Render Components can belong to Sorting Layers, which define the rendering order for sprites. Camera Components can see or not Sorting Layers by setting the Culling Mask

Game Objects and Components

Game Object
Basic entity in Unity. Can be a 3D or 2D object, a particle or audio or video source, a UI element, or an empty object. Game Objects are just containers for Compon­ents. Scripts can be attached to Game Objects, to define their behavior and proper­ties. Game Objects in your scene are repres­ented in the Hierarchy
Basic entities that implement functi­ona­lities inside Game Objects
Component in the Inspector
Each Component has a small header bar with: Turn down arrow, Icon, (De)ac­tivate checkbox, Reference book (opens online manual), Preset button, Options gear (allows to copy and paste Components).
Under the bar are all the Compon­ent's properties
Blueprint for Game Objects. You can make a Prefab out of a Game Object. The Prefab will be like a "­mod­el" from which you can instan­tiate new identical copies of that object in your game. Modifying the Prefab properties will modify all Game Objects instan­tiated from it
Any Game Object can have other Game Objects as children. The Transform of a child Game Object will be relative to the parent's Transform. If you make a Prefab out of a Game Object with children, all the hierarchy will be copied. You can see parent­/child relati­onships in the Hierarchy
Create new Game Object
Right click on the Hierarchy > select the Game Object type
Game Objects' name
Set the name from the Inspector (upper part), or from slow double click on the object in the Hierarchy
Assign custom Tags to Game Objects from the Inspector (upper part)
Add a child
In the Hierarchy, drag a Game Object over another
Add Component
Inspector > Add Component
Create Prefab
Drag the Game Object from the Hierarchy to the Project window
Create Game Object from Prefab
Drag the Prefab from the Project to the Scene view or the Hierarchy
Modify a Prefab
If you select a Prefab from the Project, and you modify its proper­tie­s/c­omp­onents, all objects of that type will be modified. On the contrary, if you modify a single Game Object, you can then, from the Inspector (upper part) click on Prefab: Apply button to modify the Prefab
Deactivate Game Object
Click the tickbox in the upper part of the Inspector
Reference Game Object in the Inspector
If you define public GameO­bject or Component (ex: Trans­form) variables in a script, they will be visible as properties in the Inspector (under the Script Compon­ent). You can assign Game Objects to these variables by dragging a Game Object from the Hierarchy to the field in the Inspector. If the variable is of type GameO­bject, you reference the whole Game Object. If it is of some Component type, instead, you will reference that Game Object's Component directly instead
Reference Prefab in the Inspector
The same way you reference a Game Object or a Component in a Script variable from the Inspector, you can drag a Prefab from the Project window to reference it. This is useful for instan­tiating copies of the Prefab later on
Instan­tiate Prefab
To instan­tiate a Prefab from a Script: define a variable of type GameO­bject or of some Component type. Reference the Prefab from the Inspector. You can now use the Insta­nti­ate() function (see API section)

Basic Game Objects and Components

Basic Game Objects
2D graphic Game Object. Contains Sprite­Ren­derer component, that manages the rendering of the texture. If you add 2D Colliders and/or 2D RigidBody Compon­ents, the Sprite will behave like a physical object
Contains a Camera component and an Audio Listener. Gives the window through which you can experience your game's world. In a new scene, there is always a Main Camera already present. You can parent a Camera to a Game Object to follow it (or setup a script that contin­ually sets the Camera's position to the Game Object's position)
Basic Compon­ents
Determines position, rotation and scale. It is always present
Display an image (Sprite property). You can create and set a Sorting Layer to define which sprite is rendered above and which below when two sprites overlap
Capture and display the world. Has several options, such as background default color, field of view. In Culling Mask you can set what layers to render and what to ignore. Game Objects belonging to ignored layers won't be seen
Defines custom properties and behavior of a Game Object

2D Physics

Physics Compon­ents
Rigidbody 2D
Places an object under control of the physics engine, giving it a Body Type (see below), a mass, a new position (overr­iding the Transf­orm's one), a velocity, an angular velocity, a Material (defining drag and bounce), and allowing it to be affected by forces (gravity, drag, impulse). Attaching a Rigidbody to a Sprite makes it behave in a physically convincing way
Collider 2D
Defines the shape for the purpose of collis­ions. Can be edited by clicking "Edit Collid­er". Can be set to "­Tri­gge­r" to emit events
Body types
Body designed to move. Collides with any body type. Can be affected by forces
Doesn't move (infinite mass). Collides with Dynamic bodies. Gives back forces when colliding
Designed to move (only via function calls). It moves accord­ingly to its velocity, but it's not affected by forces. Collides only with Dynamic bodies
Spatial coordi­nates
The position of a body is identified by a point (Vector3 with 3 coordi­nates in 3D space, Vector2 in 2D space). In games, the X axis grows from left to right, while the Y grows from top to bottom (it's reversed)
S = V * T
A body with velocity V moves by S in a timestep T
V = A * T
A body with an accele­ration A increases its velocity by V in a timestep T
F = m * A
Applying a force F to a body with mass m causes an accele­ration A on it
Static drag
If there is a static drag D on a surface, a body cannot move unless you apply a force F > D to it
Dynamic drag
If there is dynamic drag D on a surface, a body moving on it will constantly have a force D opposed to where it's moving
If there is a gravit­ational accele­ration g, a body will have a downwards accele­ration of g
Curve on which a body moves. A projectile (Angry Bird) with just an initial velocity and in a gravit­ational field will "­dra­w" a parabula shape. The projectile lands farther if the initial velocity vector was at 45°
Angular mechanics
When dealing with rotations, simply substi­tute: position with angle, velocity with angular velocity, accele­ration with angular accele­ration, force with torque, drag with angular drag. The laws stay the same


What is a script
A script is a file containing code (usually C#) that defines the properties and the behavior of a Game Object
Adding a script
Add a Script to a Game Object from Inspector > Add Component > New script
Editing a script
Double click on the script in the Inspector. It will be open with your default external editor (Visual Studio, Monode­velop). Then change the script and save it
Script contents
A script usually has import statements in the upper part, and then the code of a class (with the same name of the file), that contains variables and methods
Set variable from Inspector
From the Inspector you can set values for public variables defined in Scripts. For numbers and strings, type directly in. For GameO­bject or any Component types, drag Game Objects or Prefabs from the editor to the field
Once a script is saved, Unity automa­tically (re)co­mpiles it. It may take some time (wait for the loading gif in the bar below to disappear)
Compil­e-time errors and debug logs (outputs of Debug.L­og() ) are shown in the Console
Accessing classes from other scripts
If a Script defines a public class, you can use that class as a reference in any other Script. Ex: the script Enemy contains a reference to the class Player because it needs to chase it
From the text editor, select a term and press Ctrl + '


stat­ement ;
End every statement with a semicolon
using names­pace
Include namespace, making new classes available
class name : father { }
Define class (inher­iting from father class). A class is a blueprint that you can use to instan­tiate an object: a special variable that contains its own variables (members) and functions (methods)
public field
Make a member or method visible in the Inspector and accessible from other scripts
private field
Deny access from other scripts
// comment
One-line comment
/* multi­-line
Multiple line comment
true or false
Integer number
Decimal number. Floats always end in f. Ex: 4.5f
Array containing objects of type someType
int a;
Declaring a variable
a = 5;
Assigning a value
Clas­sName b;
Declaring a reference (variable that can contain an object)
Comp­one­ntC­lass myCom­pon­ent;
For every Component, there exist a class with the same name that you can use to refer to it (ex: Trans­form)
b = new Class­Nam­e();
Instan­tiating an object
Accessing an object's member variable
Value for null reference (a variable referring to no object)
int[] myList = new int5];
Create and assign empty array of 5 integers.
myLl­ist­[0] = 9;
Assign a value to an index of an array (indexing starts from 0)
retType Nametype1 arg1, ...) {
return X; }
Method defini­tion. Can take one or more arguments in. You must specify the type of the returned object­/va­riable. Use void if there is no return statement
obje­ct.m­ethod( )
Calling a method
Control flow
} else if (cond­ition) {
} else {
Condit­ional statement
While loop. Executes code until condi­tion is false
for(int i=X; i++; i<N){
For loop. Initia­lizes i to X and executes code as long as i<N
forea­ch(­type x in myList){
Executes code looping over myList. x is the current element of the list
+ - * / % ? ! ++ --
Operators (4 operat­ions, modulus, ternary condit­ional, not, increase, decrease)
< > == != <= >=
Relational operators (lesser, greater, equal, different, less or equal, greater or equal)
cond1 && cond2
'and' operator. True only if both conditions are true
cond1 || cond2
'or' operator. False only if both conditions are false
In italics generic or sample terms

Code Flow and Events

Code Flow
Scripts do not run in the tradit­ional manner, looping until they complete a task. Instead, Unity runs the main Game Loop (think of it as a while loop where contin­uously the following things happen: external input is taken, the game state is updated, objects may be created and destroyed, physics and graphics comput­ations are run, and a new frame is rendered on the screen). When events of a certain type happen, Unity passes control to Scripts by calling the corres­ponding function. These are called Event Functions
Event Functions
Callback functions that are called by Unity when certain events occur. Event Functions are provided as methods of the MonoBe­haviour class, from which the classes in every Script inherit
Trigger Collider
Checkbox you can tick in a Collider Component. If active, the object will emit a trigger event when in contact with something. Triggers are used for non-ph­ysical collisions (e.g. detecting when someone enters)
Mono­Beh­aviour Event Functi­ons
Called once before everything else
Called once after all Awakes, before any Update
Code that changes the position, state, behavior of objects in game. It is called before each frame is rendered. Updates happen at every iteration of the Game Loop, therefore each update may take a different time. The variable Time.d­el­taTime always contains the duration of the last update iteration
Called before each physics update. The physics engine updates in time steps of fixed duration, therefore you don't have to correct for deltaTimes when moving things inside FixedU­pdate. Place physics calls inside this
Called when there is a mouse event. *** can be: Down, Enter, Exit, Over, Up, UpAsB­utton
OnCol­lis­ion­*­**­2D(­Col­lision colli­sion)
Called when the object is involved in a collision. *** can be: Enter, Stay, Exit (contact is made, held, or broken). The parameter contains info about the collision
OnTri­gge­r*­*­*2D­(Co­llider other)
Called when the object is involved in a collision, only if the object's collider is configured as a Trigger. *** can be: Enter, Stay, Exit. The parameter is the other object's collider


Input Manager
Access in the editor by Edit > Project Settings > Input. Contains the properties of the Axes
Axes are virtual directions ("Ho­riz­ont­al", "­Ver­tic­al", "­Jum­p", "­Fir­e1",...) that represent possible inputs. Each Axis has a name, and one or two buttons that are mapped onto the Positive direction and the Negative direction (e.g. "­Fir­e1" only has a button for the Positive input, since there is no concept of firing backwa­rds)
Getting Input
When a player presses an axis button, Unity will set the axis state to a value between -1 and 1 (-1 negative, 1 positive, 0 when there is no input). Get the input by querying Axes. Altern­ati­vely, you can query using button names (Keys)
value = Input.G­et­Axi­s(­"­Hor­izo­nta­l");
Retrieves the current state for the "Ho­riz­ont­al" Axis
value = Input.G­et­Key­("a­");
Returns true if the user is holding down the key "a"


Each class inherits from MonoBe­hav­iour, inheriting members and methods that should be used for most functi­ona­lities in the Scripts
This Game Object (the Game Object to which the Script is attached)
This Game Object's Tag
This Game Object's Transform
Returns the component of type Type contained in this Game Object
Returns all components of type Type
Destr­oy(­Object obj, float t = 0.0f))`
Removes something (after t seconds). Destr­oy(­gam­eOb­ject) destroys the Game Object attached to the Script. Destr­oy(­this) destroys the Script Component itself. Destr­oy(­Get­Com­pon­ent­<...>()) destroys another Component
Insta­nti­ate­(Object origi­nal)
Clones a GameObject or Component and returns the clone. If you clone a Component, the whole GameObject it is attached to will also be cloned
Base class for all entities in Unity Scenes
Tag of this Game Object
Transform of this Game Object
SetAc­tiv­e(bool value)
Activa­te/­dea­ctivate this Game Object
Static method that finds and returns the first Game Object with tag Tag
Base class for everything attached to GameOb­jects. For every specifc component there is a class (with the same name as the Compon­ent), inheriting from this. Ex: Trans­form
Position as a Vector3
Rotation as a Quate­rnion
Rotat­e(float xAngle, float yAngle, float zAngle)
Rotate around X, Y, Z axis
Trans­lat­e(V­ector3 trans­lat­ion)
Moves position. Ex: trans­for­m.T­ran­sla­te(­Vec­tor­3.f­orw­ard­*Ti­me.d­el­taT­ime)
new Vector­2(­xy)
Create new 2D vector
new Vector­3(­xy­,z)
Create new 3D vector. Transf­orm's positions are always Vector3, even in 2D! (But you shouldn't set positions directly to move objects)
v + u, v - u
Sum/su­btract two vectors
v * 5, v / 5
Multip­ly/­divide a vector by a number
targ­et.po­sition - playe­r.p­os­ition
Vector repres­enting the distance between the two objects's Transforms
Vector's length
Vector with the same direction, but magnitude of 1
Access X component (same for Y and Z)
Prints a messaget to the Console
The body's mass. You can access all the other properties that you see from the Inspector as well
AddFo­rce­(Ve­ctor2 force)
Apply a force to the Rigidbody. Use this inside Update() for a constantly applied force
AddTo­rqu­e(float torque)
Add a torque (gives an angular accele­ration)
MoveP­osi­tio­n(V­ector2 posit­ion)
Quickly thrust towards a new position (tries to get there in the time of a physics update, but collisions or long distances may impair it). Use this in Fixed­Upd­ate() rather than in Update()

Download the Unity 2D Basics Cheat Sheet

8 Pages

PDF (recommended)

Alternative Downloads

Share This Cheat Sheet!



No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

          Numeric Formats Cheat Sheet
          Unity 2D Graphical Elements Cheat Sheet
          C# & Unity MonoBehaviour Cheat Sheet

          More Cheat Sheets by become

          Unity 2D Graphical Elements Cheat Sheet