Dev - To/codemaker2015/unity C# Cheatsheet
Dev - To/codemaker2015/unity C# Cheatsheet
Dev - To/codemaker2015/unity C# Cheatsheet
1
linkedin.com/in/codemaker2015 dev.to/codemaker2015/unity-c#-cheatsheet
Our first script
Unity uses C# as the primary scripting language. You can also write your code in Javascript but
most of them prefer C# due to its simplicity. Unity operates only with object-oriented scripting
languages. Variables, functions, and classes are the primary building block of any language. The
following is a basic script in Unity with a log message.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HelloWorld : MonoBehaviour
{
//Variables
//Functions
//Classes
// Start is called before the first frame update
void Start()
{
Debug.Log("Hello World");
}
// Update is called once per frame
void Update()
{
}
}
1. Variables
It is the name of a memory location which holds values and references of an object. Like any
object orient programming language, the variable declaration contains the accessibility level
(scope). It can be public, private or protected.
Unity made the object referencing simple by showing the public variables in the inspector. So,
the user can easily provide values or references to that variable from the inspector.
If we want to refer to any gameObject in the script then make its visibility public or put a
SerializeField tag there.
2
linkedin.com/in/codemaker2015 dev.to/codemaker2015/unity-c#-cheatsheet
2. Classes
Classes are the blueprint of the objects. It is a template that wraps variables and functions
together.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class HelloWorld : MonoBehaviour
{
public GameObject gameObject1;
private GameObject gameObject2;
// Start is called before the first frame update
void Start()
{
Display();
}
// Update is called once per frame
void Update()
{
}
void Display()
{
Debug.Log("Hello World");
}
}
3. Functions
Functions are a set of codes executed to accomplish a specific task. It helps to create reusable
codes and implement modularity in your app. Also, we use functions to make our codes readable
and portable.
Unity has a couple of life cycle methods such as Awake(), Start(), Update(), and these methods
call automatically when some predefined conditions are met.
3
linkedin.com/in/codemaker2015 dev.to/codemaker2015/unity-c#-cheatsheet
// Called every Fixed Timestep
private void FixedUpdate() {}
// Called when the renderer is visible by any Camera
private void OnBecameVisible() {}
// Called when the renderer is no longer visible by any Camera
private void OnBecameInvisible() {}
// Allows you to draw Gizmos in the Scene View
private void OnDrawGizmos() {}
// Called multiple times per frame in response to GUI events
private void OnGUI() {}
// Called at the end of a frame when a pause is detected
private void OnApplicationPause() {}
// Called every time the object is disabled
private void OnDisable() {}
// Only called on previously active GameObjects that have been destroyed
private void OnDestroy() {}
4
linkedin.com/in/codemaker2015 dev.to/codemaker2015/unity-c#-cheatsheet
Figure 0-1 Image credits docs.unity3d.com
4. GameObject Manipulation
GameObject is the core component of a Unity project. All objects such as light, UI and 3D
models are derived from GameObjects class. This is the parent class for all objects we are using
in a unity scene.
In Unity, we can interact with the GameObjects in two ways — through the inspector and using a
script. If you want to change the object position then you can easily do it through the inspector
window.
5
linkedin.com/in/codemaker2015 dev.to/codemaker2015/unity-c#-cheatsheet
// Create a GameObject
Instantiate(GameObject prefab);
Instantiate(GameObject prefab, Transform parent);
Instantiate(GameObject prefab, Vector3 position, Quaternion rotation);
Instantiate(bullet);
Instantiate(bullet, bulletSpawn.transform);
Instantiate(bullet, Vector3.zero, Quaternion.identity);
Instantiate(bullet, new Vector3(0, 0, 10), bullet.transform.rotation);
// Destroy a GameObject
Destroy(gameObject);// Finding GameObjects
GameObject myObj = GameObject.Find("NAME IN HIERARCHY");
GameObject myObj = GameObject.FindWithTag("TAG");
// Accessing Components
Example myComponent = GetComponent<Example>();
AudioSource audioSource = GetComponent<AudioSource>();
Rigidbody rgbd = GetComponent<Rigidbody>();
5. Input System
The input system is the crucial component in every game that we have played. It might be a
keyboard, joystick, or touch. Unity has a Conventional Game Input to access input in your
games.
if (Input.GetKeyDown(KeyCode.Space)) {
Debug.Log("Space key was Pressed");
}
if (Input.GetKeyUp(KeyCode.W)) {
Debug.Log("W key was Released");
}
if (Input.GetKey(KeyCode.UpArrow)) {
Debug.Log("Up Arrow key is being held down");
}
/* Button Input located under Edit >> Project Settings >> Input */
if (Input.GetButtonDown("ButtonName")) {
Debug.Log("Button was pressed");
}
if (Input.GetButtonUp("ButtonName")) {
Debug.Log("Button was released");
}
if (Input.GetButton("ButtonName")) {
Debug.Log("Button is being held down");
}
6
linkedin.com/in/codemaker2015 dev.to/codemaker2015/unity-c#-cheatsheet
6. Vector
Vector is a mathematical concept that holds both magnitude and direction. It is useful to describe
some properties such as the position and velocity of a moving object in your game, or the
distance between two objects. Unity implements Vector2 and Vector3 classes for working with
2D and 3D vectors.
7. Time
Unity supports time-related operations through its Time library. Time.time, Time.deltaTime
and Time.timeScale are the most common APIs to work with time in your project.
7
linkedin.com/in/codemaker2015 dev.to/codemaker2015/unity-c#-cheatsheet
8. Physics Events
Unity has a sophisticated system to implement physics in your project. It various physics
attributes to the gameObjects such as gravity, acceleration, collision and other forces.
/* Both objects have to have a Collider and one object has to have a
Rigidbody for these Events to work */
private void OnCollisionEnter(Collision hit) {
Debug.Log(gameObject.name + " hits " + hit.gameObject.name);
}
private void OnCollisionStay(Collision hit) {
Debug.Log(gameObject.name + " is hitting " + hit.gameObject.name);
}
private void OnCollisionExit(Collision hit) {
Debug.Log(gameObject.name + " stopped hitting " + hit.gameObject.name);
}
// For 2D Colliders
private void OnCollisionEnter2D(Collision2D hit) { }
private void OnCollisionStay2D(Collision2D hit) { }
private void OnCollisionExit2D(Collision2D hit) { }
private void OnTriggerEnter2D(Collider2D hit) { }
private void OnTriggerStay2D(Collider2D hit) { }
private void OnTriggerExit2D(Collider2D hit) { }
9. Rendering materials
Materials tell how a surface should be rendered in the scene. The material contains references to
shaders, textures, color, emission and more. Every material requires a shader for rendering the
content and the attributes available for that may vary on different shader values.
8
linkedin.com/in/codemaker2015 dev.to/codemaker2015/unity-c#-cheatsheet
[SerializeField] Material material;
[SerializeField] Texture2D texture;
[SerializeField] Color color = Color.red;
10. Lighting
Lighting is a mandatory component in any Unity scene. All unity scenes contain a directional
light component in it by default. Unity has four types of lights — directional, points, spot and area
lights
void Update() {
if (Input.GetKey(KeyCode.UpArrow))
lightComp.GetComponent<Light>().enabled = true;
if (Input.GetKey(KeyCode.DownArrow))
lightComp.GetComponent<Light>().enabled = false;
}
9
linkedin.com/in/codemaker2015 dev.to/codemaker2015/unity-c#-cheatsheet
11. Coroutine
A coroutine is like a background activity which can hold the execution of codes after the yield
statement until it returns a value.
// Create a Coroutine
private IEnumerator CountSeconds(int count = 10)
{
for (int i = 0; i <= count; i++) {
Debug.Log(i + " second(s) have passed");
yield return new WaitForSeconds(1.0f);
}
}
// Call a Coroutine
StartCoroutine(CountSeconds());
StartCoroutine(CountSeconds(10));
12. Animation
It is an easy task to create animations in Unity. Unity made it simple with the help of Animator
controls and Animation Graph. Unity calls the animator controllers to handle which animations
to play and when to play them. The animation component is used to playback animations.
10
linkedin.com/in/codemaker2015 dev.to/codemaker2015/unity-c#-cheatsheet
It is quite simple to interact with the animation from a script. First, you have to refer the
animation clips to the animation component. Then get the Animator component reference in the
script via GetComponent method or by making that variable public. Finally, set enabled
attribute value to true for enabling the animation and false for disabling it.
13. Hotkeys
11
linkedin.com/in/codemaker2015 dev.to/codemaker2015/unity-c#-cheatsheet