Editor's Interface
Scene view |
Build the game world, interact with game objects |
Game view |
Preview and play game (pressing Play in Toolbar) |
Inspector |
Show and modify game objects' components' properties |
Hierarchy |
Game objects in game |
Project |
Assets available |
Toolbar |
Bar with buttons at the top. Contains transform tools, play controls, layers and layout |
Assets |
Files (scripts, textures, models, prefabs) |
Console |
Contains debug logs and errors |
Tags, Layers, Sorting Layers |
Open from Edit > Project Settings > Tags and Layers. Tags are identifiers for Game Objects. Game Objects can belong to Layers. Objects in last Layers are rendered above the others. SpriteRender 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 Components. Scripts can be attached to Game Objects, to define their behavior and properties. Game Objects in your scene are represented in the Hierarchy |
Component |
Basic entities that implement functionalities inside Game Objects |
Component in the Inspector |
Each Component has a small header bar with: Turn down arrow, Icon, (De)activate checkbox, Reference book (opens online manual), Preset button, Options gear (allows to copy and paste Components). Under the bar are all the Component's properties |
Prefab |
Blueprint for Game Objects. You can make a Prefab out of a Game Object. The Prefab will be like a "model" from which you can instantiate new identical copies of that object in your game. Modifying the Prefab properties will modify all Game Objects instantiated from it |
Parent/Child |
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 relationships in the Hierarchy |
Usage |
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 |
Tag |
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 properties/components, 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 GameObject
or Component (ex: Transform
) variables in a script, they will be visible as properties in the Inspector (under the Script Component). 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 GameObject
, 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 instantiating copies of the Prefab later on |
Instantiate Prefab |
To instantiate a Prefab from a Script: define a variable of type GameObject
or of some Component type. Reference the Prefab from the Inspector. You can now use the Instantiate()
function (see API section) |
Basic Game Objects and Components
Basic Game Objects |
Sprite |
2D graphic Game Object. Contains SpriteRenderer component, that manages the rendering of the texture. If you add 2D Colliders and/or 2D RigidBody Components, the Sprite will behave like a physical object |
Camera |
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 continually sets the Camera's position to the Game Object's position) |
Basic Components |
Transform |
Determines position, rotation and scale. It is always present |
SpriteRenderer |
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 |
Camera |
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 |
Script |
Defines custom properties and behavior of a Game Object |
|
|
2D Physics
Physics Components |
Rigidbody 2D |
Places an object under control of the physics engine, giving it a Body Type (see below), a mass, a new position (overriding the Transform'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 collisions. Can be edited by clicking "Edit Collider". Can be set to "Trigger" to emit events |
Body types |
Dynamic |
Body designed to move. Collides with any body type. Can be affected by forces |
Static |
Doesn't move (infinite mass). Collides with Dynamic bodies. Gives back forces when colliding |
Kinematic |
Designed to move (only via function calls). It moves accordingly to its velocity, but it's not affected by forces. Collides only with Dynamic bodies |
Mechanics |
Spatial coordinates |
The position of a body is identified by a point (Vector3 with 3 coordinates 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 acceleration 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 acceleration 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 |
Gravity |
If there is a gravitational acceleration g, a body will have a downwards acceleration of g |
Trajectory |
Curve on which a body moves. A projectile (Angry Bird) with just an initial velocity and in a gravitational field will "draw" a parabula shape. The projectile lands farther if the initial velocity vector was at 45° |
Angular mechanics |
When dealing with rotations, simply substitute: position with angle, velocity with angular velocity, acceleration with angular acceleration, force with torque, drag with angular drag. The laws stay the same |
Scripting
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, Monodevelop). 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 GameObject
or any Component types, drag Game Objects or Prefabs from the editor to the field |
Compiling |
Once a script is saved, Unity automatically (re)compiles it. It may take some time (wait for the loading gif in the bar below to disappear) |
Debugging |
Compile-time errors and debug logs (outputs of Debug.Log() ) 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 |
Documentation |
From the text editor, select a term and press Ctrl + ' |
C#
Syntax |
|
End every statement with a semicolon |
|
Include namespace, making new classes available |
|
Define class (inheriting from father class). A class is a blueprint that you can use to instantiate an object: a special variable that contains its own variables (members) and functions (methods) |
|
Make a member or method visible in the Inspector and accessible from other scripts |
|
Deny access from other scripts |
|
One-line comment |
|
Multiple line comment |
Types |
|
|
|
Integer number |
|
Decimal number. Floats always end in f. Ex: 4.5f
|
|
Text |
|
Array containing objects of type someType |
Variables |
|
Declaring a variable |
|
Assigning a value |
|
Declaring a reference (variable that can contain an object) |
ComponentClass myComponent;
|
For every Component, there exist a class with the same name that you can use to refer to it (ex: Transform
) |
|
Instantiating an object |
|
Accessing an object's member variable |
|
Value for null reference (a variable referring to no object) |
int[] myList = new int[5];
|
Create and assign empty array of 5 integers. |
|
Assign a value to an index of an array (indexing starts from 0) |
Methods |
retType Name(type1 arg1, ...) { body return X; }
|
Method definition. Can take one or more arguments in. You must specify the type of the returned object/variable. Use void
if there is no return statement |
|
Calling a method |
Control flow |
if(condition){ code } else if (condition) { code } else { code}
|
Conditional statement |
|
While loop. Executes code until condition is false |
for(int i=X; i++; i<N){ code}
|
For loop. Initializes i to X and executes code as long as i<N |
foreach(type x in myList){ code}
|
Executes code looping over myList. x is the current element of the list |
Operators |
+ - * / % ? ! ++ -- |
Operators (4 operations, modulus, ternary conditional, not, increase, decrease) |
< > == != <= >= |
Relational operators (lesser, greater, equal, different, less or equal, greater or equal) |
|
'and' operator. True only if both conditions are true |
|
'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 traditional manner, looping until they complete a task. Instead, Unity runs the main Game Loop (think of it as a while
loop where continuously the following things happen: external input is taken, the game state is updated, objects may be created and destroyed, physics and graphics computations 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 corresponding 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 MonoBehaviour 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-physical collisions (e.g. detecting when someone enters) |
MonoBehaviour Event Functions |
|
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.deltaTime
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 FixedUpdate. Place physics calls inside this |
|
Called when there is a mouse event. *** can be: Down
, Enter
, Exit
, Over
, Up
, UpAsButton
|
OnCollision***2D(Collision collision)
|
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 |
OnTrigger***2D(Collider 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
Input Manager |
Access in the editor by Edit > Project Settings > Input. Contains the properties of the Axes |
Axes |
Axes are virtual directions ("Horizontal", "Vertical", "Jump", "Fire1",...) 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. "Fire1" only has a button for the Positive input, since there is no concept of firing backwards) |
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. Alternatively, you can query using button names (Keys) |
value = Input.GetAxis("Horizontal");
|
Retrieves the current state for the "Horizontal" Axis |
value = Input.GetKey("a");
|
Returns true
if the user is holding down the key "a" |
API
MonoBehaviour |
|
Each class inherits from MonoBehaviour, inheriting members and methods that should be used for most functionalities 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 |
Destroy(Object obj, float t = 0.0f)
)` |
Removes something (after t seconds). Destroy(gameObject)
destroys the Game Object attached to the Script. Destroy(this)
destroys the Script Component itself. Destroy(GetComponent<...>())
destroys another Component |
Instantiate(Object original)
|
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 |
GameObject |
|
Base class for all entities in Unity Scenes |
|
Tag of this Game Object |
|
Transform of this Game Object |
|
Activate/deactivate this Game Object |
GameObject.FindWithTag("Tag")
|
Static method that finds and returns the first Game Object with tag Tag |
Component |
|
Base class for everything attached to GameObjects. For every specifc component there is a class (with the same name as the Component), inheriting from this. Ex: Transform
|
Transform |
|
|
|
|
Rotate(float xAngle, float yAngle, float zAngle)
|
Rotate around X, Y, Z axis |
Translate(Vector3 translation)
|
Moves position. Ex: transform.Translate(Vector3.forward*Time.deltaTime)
|
Vector |
|
Create new 2D vector |
|
Create new 3D vector. Transform's positions are always Vector3, even in 2D! (But you shouldn't set positions directly to move objects) |
|
Sum/subtract two vectors |
|
Multiply/divide a vector by a number |
target.position - player.position
|
Vector representing 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) |
Debugging |
Debug.Log(*"message");
|
Prints a messaget to the Console |
Rigidbody2D |
|
The body's mass. You can access all the other properties that you see from the Inspector as well |
AddForce(Vector2 force)
|
Apply a force to the Rigidbody. Use this inside Update()
for a constantly applied force |
AddTorque(float torque)
|
Add a torque (gives an angular acceleration) |
MovePosition(Vector2 position)
|
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 FixedUpdate()
rather than in Update()
|
|
Created By
https://becomeagamedeveloper.github.io/site
Metadata
Favourited By
Comments
No comments yet. Add yours below!
Add a Comment
Related Cheat Sheets
More Cheat Sheets by become