1 of 8

Unity Lecture #5:

Advanced Code Tips

Copyright 2022 © Extended Reality at Berkeley

2 of 8

Randomization

  • Random.value - float between 0 and 1
  • Random.Range(min, max)

2

3 of 8

Time

  • Time.time - seconds since project started playing
  • Time.deltaTime
    • Amount of time (seconds) passed since last frame (works with Update)

3

Void Update(){

seconds += Time.deltaTime;

}

4 of 8

Enumerations (Enum)

  • Define different states
  • Might be easier than having multiple True/False variables

4

enum EnemyState {Run, Walk, Attack};

EnemyState currentState;

Void Start(){

currentState = EnemyState.Run;

}

isRunning = true;

isWalking = false;

isAttacking = false;

5 of 8

Coroutines

  • Allows you to time events in a sequence
  • IEnumerator

5

IEnumerator Attack(){

Do something

Yield return null;

Do something else

}

6 of 8

Coroutines (cont)

  • Yield return null
    • Waits for 1 frame
  • Yield return new WaitForSeconds(1f)
    • Waits for 1 second
  • Yield return new WaitUntil (() => someCondition)
    • Waits until some condition is met

6

7 of 8

Manager

  • One general script is in charge of the pipeline
    • Running everything in the background
  • Example
    • Multiple enemies, but 1 enemy manager to keep track of them all
  • Simple as having a separate GameObject with a Manager script in the Scene

7

8 of 8

Null Reference Exceptions

  • Always check if things are null!
    • Scripts not being assigned on runtime, and you try to call a method from that script

8