Unity Programming Quick Reference
Unity Programming Quick Reference
x=x+1 x++
Conditionals
y=y+1 y-- if (condition1) {
// do this
x=x+y x+=y } else if (condition2) {
// do that
x=x-y x-=y } else {
// do default
}
Logic switch(name) {
case "brian":
Logic Symbol Debug.Log("Welcome Brian");
break;
Equal == case "will":
Debug.Log("Welcome Will");
Not Equal != break;
default:
Greater Than > Debug.Log("I don’t know you");
break;
Greater Than or Equal To >= }
1 of 2
C# and Unity API
Typical C# Script Template Referencing Components
using System.Collections; You can get a reference to a component in the following ways:
using System.Collections.Generic;
using UnityEngine; Setup a public variable that holds the reference that you set in the
Editor, such as:
public class BasicTargetMover : MonoBehaviour {
public AudioSource backgroundMusic;
// Use this for initialization
Get the component through a reference to a gameObect, such as:
void Start () {
gameObject.GetComponent<AudioSource>();
}
The Transform component has a shortcut.
// Update is called once per frame
void Update () { gameObject.transform
} Instantiating Prefabs
}
You can dynamically create, or instantiate gameObjects in a
Important concepts in Unity scene from other gameObjects or Prefabs:
• MonoBehavior is the base class that all Unity GameObject GameObject spawnedObject = Instantiate
scripts are derived from. (prefabObject, spawnPosition, spawnRotation) as
• Public variables are exposed in the editor GameObject;
• Public variables and functions can be accessed when you
have a reference to the component
• You can make an Object global by creating a public static Common Game Events
variable
Awake & Start - called once. This is where you can set things up.
Referencing GameObjects
Update - is called every game cycle before rendering a frame.
You can reference a gameObject in code in the following ways: This is where most game behaviour code goes, except physics
code.
If the script is attached to the gameObject, you can reference the FixedUpdate - is called once every physics time step. This is the
gameObject as: place to do physics-based game behaviour.
this.gameObject or simply gameObject OnCollisionEnter is called when this collider/rigidbody has begun
touching another rigidbody/collider.
If we want to reference a gameObject that the script is NOT
attached to, we can do this in a number of ways: OnTriggerEnter is called when this collider has touched another
collider that is tagged as a trigger.
We can have a public variable of type GameObject that we attach Useful API Classes
to another gameObject or prefab in the Unity Editor.
GameObject, Time, Transform, RigidBody, AudioSource
public GameObject target; (look in documentation for details and other UnityEngine classes)
2 of 2