I’ve tried making a game some months ago, for that I’ve learned some c#, but I’ve suspended that project because I wanted to finish high school first. It’s finished now, so I’ve started to learn c# from the ground up again, here are some notes I’ve taken in the first day.

Change GameObject Position

public Vector3 startingPos = new Vector3(0, 0, 0); void Start() { transform.position = startingPos; }

GetKey variants

void Update() { //GetKeyDown detects when you press a key if (Input.GetKeyDown(KeyCode.Space)) { print("Space has been pressed"); } //GetKey detects when you're holding down a key if (Input.GetKey(KeyCode.Space)) { print("Space is being pressed"); } //GetKeyUp detects when you release a key if (Input.GetKeyUp(KeyCode.Space)) { print("Space has been released"); } }

Moving with Axis

[SerializeField] float speed = 5f; // Speed variable void Update() { // Storing the value of the axis input to a float (-1 = left ; 1 = right) float horizontalAxis = Input.GetAxis("Horizontal"); // Storing the value of the axis input to a float (-1 = down ; 1 = up) float verticalAxis = Input.GetAxis("Vertical"); // Translate the object using the axis, multiplying by the variable of speed and multiplying by deltatime transform.Translate(new Vector3(horizontalAxis, verticalAxis, 0) * speed * Time.deltaTime); }

Simple Collectibles

// Collectible needs to be a Trigger, needs Rigidbody private void OnTriggerEnter(Collider other) // The object's collider that collides with the Collectibe is stored on 'other' { if(other.tag == "Player") // Checks if the object that collided has the tag 'Player' { Destroy(this.gameObject); // Destroy Collectible if true } }

Pause Game

bool isPaused = false; // bool to detect if the game is paused void Update() { if (Input.GetKeyDown(KeyCode.Space) && !isPaused) // If it isn't paused and you press 'space' { Time.timeScale = 0; // pause game isPaused = true; // set 'isPaused' to true }else if (Input.GetKeyDown(KeyCode.Space) && isPaused) // Instead, if you press 'space' and the game is paused { Time.timeScale = 1; // unpause the game isPaused = false; // set 'isPaused' to false }

Quaternion on Instantiate

[SerializeField] GameObject cubePrefab; // Prefab to Instantiate void Update() { if (Input.GetKeyDown(KeyCode.Space)) { // Instantiate at world origin, with a rotation of 35 euler angles on the y axis. Instantiate(cubePrefab, Vector3.zero, Quaternion.Euler(0, 35, 0)); } }

Rotating as Quaternion is useful to avoid gimbal locking, rotations in Unity occur as Quaternion, yet they’re represented as euler angles.

Look at Quaternion

[SerializeField] Transform sphere; void Update() { // Calculates distance from the object to the target Vector3 distanceToSphere = sphere.position - transform.position; // Draws a ray in Play mode from the object to the target (object, target, ray color) Debug.DrawRay(transform.position, sphere.position, Color.green); // Makes the object look at the target transform.rotation = Quaternion.LookRotation(distanceToSphere); }

To make a smoother movement, we need to save the LookRotation to a Quaternion variable, and use the Slerp function to smooth the movement.

// Saves the LookAt into a Quaternion variable Quaternion targetRotation = Quaternion.LookRotation(distanceToSphere); // Slerps (smooth) the transition from the current rotation to the new rotation of the target. transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * 5); }

Calculating random quiz grades

// define quiz floats float quiz1, quiz2, quiz3, quiz4, quiz5; void Start() { // assign a random grade quiz1 = Random.Range(1, 12); quiz2 = Random.Range(1, 12); quiz3 = Random.Range(1, 12); quiz4 = Random.Range(1, 12); quiz5 = Random.Range(1, 12); // calculate the average float quizAverage = ((quiz1 + quiz2 + quiz3 + quiz4 + quiz5) / 5); // print the average, rounds the average, multiply and then divide by the same number. // number of zeroes indicate number of decimals print("The average is: " + Mathf.Round(quizAverage * 10f) / 10f); }

Small note on variables syntax

Use underscore for private variables:

int _age; public int age;

Changing material color based on score

[SerializeField] MeshRenderer _cubeMaterial; // get MeshRenderer from player [SerializeField] int _score; // assign score variable void Start() { // set material color from player to red at start _cubeMaterial.material.SetColor("_Color", Color.red); } void Update() { // add 10 to score when player presses space if (Input.GetKeyDown(KeyCode.Space)) { _score += 10; print(_score); } // turn player material color to green when score is greater than 50 if(_score > 50) { _cubeMaterial.material.SetColor("_Color", Color.green); } }

Switch statement syntax

int caseSwitch = 1; switch (caseSwitch) { case 1: Console.WriteLine("Case 1"); break; case 2: Console.WriteLine("Case 2"); break; default: Console.WriteLine("Default case"); break; }

For Loop syntax

for(int i = 100; i > 0; i--) // define variable, condition, increment var { if(i % 2 == 0) // prints even numbers { print(i); } }

Do-while loop

Runs at least once, then checks if condition is true

int i = 0; do { print(i); if(i <= 50) { I++; // incrementer } } while (i < 50);

While loop syntax

void Start() { StartCoroutine("WhileLoop"); } IEnumerator WhileLoop() { while (true) { yield return new WaitForSeconds(1.0f); print("Prints each second forever"); } }

Break

Used to stop a loop before it ends

for(int i = 0; i < 100; i++) { print(i); if(i == 50) { break; } }

Arrays

public string[] names; // most used public string[] names = new string[5]; public string[] names = new string[] { "Jonathan", "Simon", "Alicia", "Lila" };

Printing each item in Array with for loop

if (Input.GetKeyDown(KeyCode.Space)) { for(int i = 0; i < names.Length; i++) { print(names[i]); // prints each item on names[] } }

Printing each item in Array with foreach

if (Input.GetKeyDown(KeyCode.Space)) { foreach(var name in names) // foreach object 'name' in array 'names' { print(name); } }

Public Item Class

[System.Serializable] public class Item { public int itemID; public string name; public string description; } public class array : MonoBehaviour { // creates an array of class Item // each item in myItems includes itemID ; name ; description public Item[] myItems; void Update() { if (Input.GetKeyDown(KeyCode.Space)) { foreach(var item in myItems) { print(item.itemID); print(item.name); print(item.description); } } } }

Set color to each cube in array

[SerializeField] GameObject[] cubes; private void Update() { if (Input.GetKeyDown(KeyCode.Space)) { foreach(var cube in cubes) { cube.GetComponent<MeshRenderer>().material.color = Color.green; } } } /* Using a for loop instead for(int i = 0; i < cubes.Length; i++) { cubes[i].GetComponent<MeshRenderer>().material.color = Color.green; } */

So, that concludes the first day of learning Unity again.

From Unity Learn Premium