Please enable JavaScript to use CodeHS

Unity C# Documentation


Resources


Unity Script Boilerplate

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Boilerplate : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

    }
}

Unity Docs


Variables in Unity

When you declare public variables in your MonoBehaviour class of a script, the properties and values of a GameObject can be configured and adjusted in the Unity Inspector.


Variable Types

  • string = Stores a string of characters or text
  • int = Stores an integer or whole number
  • bool = Stores a Boolean value of true or false
  • float = Stores a floating point number or integer with a decimal point
// Example Variables

public string myText;  // Can be changed in Inspector
private int coins = 0; // Cannot be changed in Inspector
private bool isGrounded = false;
public float speed = 2.3f;  // Must use 'f' with values

Note: You can also use var to let Unity infer the variable type based on the value you assign it.


Unity Variable Types

  • Vector2 = Represents 2D positions or directions (x and y coordinates)
  • Vector3 = Represents 3D positions or directions (x, y, and z coordinates)
  • GameObject = References a game object in the scene Hierarchy
  • AudioClip = Stores an audio file's information
// Example Unity Variables

private Vector2 circlePosition = new Vector2(25, 164);
private Vector3 cubePosition = new Vector3(64, 64, 24);
public GameObject player;   // GameObject is assigned in Unity Inspector
public AudioClip roar;      // Audio file is assigned in Unity Inspector

Note: You can also use var to let Unity infer the variable type based on the value you assign it.

For more resources, check out the Unity Docs: Variables and the Inspector.


Logical Operators

C# programming language offers three main logical operators to combine Boolean expressions. These can be used to check the states of game elements as conditions in if-statements.


Logical AND (&&)

This operator requires both conditions to be true for the entire expression to be true. It behaves like "and" in English.

// Example

private bool isGrounded = true;
private bool isRunning = true;

if (isGrounded && isRunning)
{
    // Do Something
}

Logical OR (||)

This operator requires only one condition to be true for the entire expression to be true. It behaves like "or" in English.

// Example

private bool isGrounded = false;
private bool hasPowerUp = true;

if (isGrounded || hasPowerUp)
{
    // Do Something
}

Binary OR (|)

This operator requires only one condition to be true for the entire expression to be true, but checks each condition individually in a sequence. In most cases, (||) logical OR operator is used to check Boolean game states.

// Example

private bool isGrounded = true;
private bool hasPowerUp = true;

// For example, since isGrounded is true, hasPowerUp is not checked.
if (isGrounded | hasPowerUp)
{
    // Do Something
}

Logical NOT (!)

This operator inverts the truth value of a single condition. It's like saying "not" in English.

// Example

private bool isGrounded = false;

if (!isGrounded)
{
    // Code to let player push a button
    // to make their character jump
}

Comparison Operators

Checks if two operands or conditionals have the same value.


== (Equal)

// Example

int x = 5;
bool isFive = (x == 5); // isFive will be true

!= (Not equal)

Checks if two operands or conditionals are different.

// Example

string name = "Clyde";
bool notClyde = (name != "Pinky"); // notClyde will be true

< (Less than)

Checks if the left operand is less than the right operand.

// Example

float pi = 3.14;
bool lessThanFour = (pi < 4.0); // lessThanFour will be true

> (Greater than)

Checks if the left operand is greater than the right operand.

// Example

int age = 25;
bool olderThanTwenty = (age > 20); // olderThanTwenty will be true

<= (Less than or equal to)

Checks if the left operand is less than or equal to the right operand.

// Example

int score = '3';
bool goodScore = (score <= '5'); // goodScore will be true

>= (Greater than or equal to)

Checks if the left operand is greater than or equal to the right operand.

// Example

float temp = 98.6f; bool hasFever = (temp >= 100.0f); // hasFever will be false

Classes


AudioSource

Representation of an audio source in a 2D or 3D game environment.

Properties

  • clip = Default AudioClip to play
  • isPlaying = Check if clip is playing
  • loop = Check if clip is looping
  • playOnAwake = If true, audio source will automatically start playing when game begins
  • volume = Volume of the audio source (0.0 to 1.0)

Methods

  • Play = Plays the clip
  • PlayOneShot = Plays an AudioClip and scales the volume by volumeScale
  • Stop = Stops playing audio clip

// Example

public AudioClip roar;
private AudioSource audioSource;

void Start()
{
    audioSource = GetComponent<AudioSource>();
}

void Update()
{
    // Sound effect of roar is played if not playing already
    if (audioSource != null && !audioSource.isPlaying)
    {
        audioSource.PlayOneShot(roar);
    }
}

Collision

Describes a collision with another object.

Methods

  • gameObject = Info of the collided object (note the lowercase 'g')

// Examples

if (collision.gameObject == player)
    {
        // Do something
    }

if (collision.gameObject.tag == "Collectible")
    {
        // Do something
    }

Debug

Call containing methods to ease debugging while developing a game.

Methods

  • DrawLine = Draws line between two points in Play mode
  • Log = Logs a message to the Unity Console

// Examples

// Draw a 5-unit white line from the origin for 2.5 seconds
Debug.DrawLine(Vector3.zero, new Vector3(5, 0, 0), Color.white, 2.5f);

// Print statement to track number of collectibles to debug HUD 
private gems = 0;
Debug.Log("Gems Collected: " + gems);

GameObject

Base class for all game objects and entities in Unity Scenes.

Methods

  • Destroy = Removes GameObject, component, or an asset
  • GetComponent = Gets reference to a component of the GameObject
  • Instantiate = Clones the GameObject (primarily used with prefabs)

// Examples

// Destroy and clear the timer if the menu screen is loaded
if (currentScene.name == "MenuScreens")
{
    Destroy(gameObject);
}

// Get Rigidbody2D component of GameObject and assign to a variable
private Rigidbody2D rb2d;
void Start()
{
    rb2d = player.GetComponent<Rigidbody2D>();
}

// Clone ski track prefab behind a skier GameObject character
private float skiTrackTime = 0.1f;
public GameObject skiTrackPrefab;

void SpawnSkiTrack()
{
    if (Input.GetAxis("Horizontal") == 0)
    {
        // Assign GameObject-type variable to clone a ski tracks prefab object
        // Assign position and rotation of clones to attached skier GameObject
        GameObject skiTrack = Instantiate(skiTrackPrefab, transform.position, transform.rotation);

        // Move ski track clones above the skier GameObject if script attached to the skier GameObject
        skiTrack.transform.position = new Vector2(this.transform.position.x, this.transform.position.y + 1.1f);

        // Destroy ski track clones when time float variable is reached
        Destroy(skiTrack, skiTrackTime);
    }
}

Input

Interface into the Input system.

KeyCode maps to physical keys only if "Use Physical Keys" is enabled in Input Manager settings, otherwise it maps to layout and platform dependent key mapping. (This is enabled by default.)

This class is used to read axes set up in Input Manager Settings. It can also be used to access multi-touch and accelerometer data on mobile devices.

Methods

  • GetAxis = Returns value of the virtual axis identified by either "Horizontal" or "Vertical"
  • GetKey = Returns true while the user holds down the key identified by name

// Examples

// Get value of horizontal input
float xInput = Input.GetAxis("Horizontal") * speed;

// Get value of vertical input
float yInput = Input.GetAxis("Vertical") * speed;

// While space bar is pressed, variable jumpInput is set to 1
if (Input.GetKey(KeyCode.Space))
{
    jumpInput = 1;
}

Mathf

Contains a collection of common math functions using single floating point calculations.

Methods

  • Abs = Returns the absolute value of a float
  • FloorToInt = Returns the largest integer smaller than or equal to a float
  • PingPong = Returns a value that increments or decrements (increases or decreases) between zero and the length or float provided

// Examples

// Converts float value of time to an integer smaller than or equal to the float time
int minutes = Mathf.FloorToInt(120.48f / 60f);

// Use PingPong class to bounce between two points a specified speed and distance
// Elapsed time multiplied by speed, distance to bounce between, plus starting position on y-axis
float y = Mathf.PingPong(Time.time * 0.5, 0.8) + transform.position.y;

MonoBehaviour

The base class that many Unity scripts derive from.

Methods

  • Invoke = Calls a method (or function) after a delay in seconds

Messages

  • FixedUpdate = Function that updates scene frame after physics calculations
  • OnCollisionEnter = Called when collider/rigidbody begins touching another collider/rigidbody
  • OnCollisionEnter2D = Called only when two colliders make contact (2D physics only)
  • OnCollisionExit = Called when collider/rigidbody stops touching another collider/rigidbody
  • OnCollisionExit2D = Called only when two colliders stop making contact (2D physics only)
  • OnControllerColliderHit = Called when controller hits a collider while performing a move
  • OnMouseDown = Called when user has pressed the mouse button while over a Collider
  • Start = Method/function called when a script starts for the first time in a Scene
  • Update = Method/function called every frame

// Examples

// Invoke a method/function to restart a scene with a delay
Invoke("RestartScene", 5f);

void FixedUpdate()
{
    // Do something
}

void OnCollisionEnter2D(Collision2D collision)
{
    if (collision.gameObject == Yeti)
    {
        inputEnabled = false;
    }
}

void OnCollisionExit2D(Collision2D collision)
{
    if (collision.gameObject == Yeti)
    {
        inputEnabled = true;
    }
}

// only for GameObjects with a character controller applied
void OnControllerColliderHit(ControllerColliderHit hit)
{
    Rigidbody body = hit.collider.attachedRigidbody;
    if (hit.gameObject.tag == "Enemy")
    {
        Destroy(hit.gameObject);
    }
}

// Change color of sprite to "newColor" when mouse pressed
void OnMouseDown()
{
    spriteRenderer.color = newColor;
}

void Start()
{
    // Do something once when script starts
}

void Update()
{
    // Do something every frame
}

Time

Provides an interface to get time info from Unity.

Properties

  • deltaTime = Interval in seconds from the last frame to the current one

// Examples

// Move GameObject using new vector 'direction' and a set 'speed' float variable
transform.Translate(direction * Time.deltaTime * speed);

// Increment the variable 'elapsedTime' by deltaTime
elapsedTime += Time.deltaTime;

Vector2

Representation of 2D vectors and points.

Properties

  • down = Shorthand for Vector2(0, -1)
  • left = Shorthand for Vector2(-1, 0)
  • right = Shorthand for Vector2(1, 0)
  • up = Shorthand for Vector2(0, 1)
  • zero = Shorthand for Vector2(0, 0)
  • x = X-axis component of the vector
  • y = Y-axis component of the vector

// Example

public float speed = 2; // Default pixels per second

void Update()
{
    // Get sprite's current position
    Vector2 position = transform.position;

    // Move sprite to the right at the specified speed
    position += (Vector2.right + Vector2.up) * speed * Time.deltaTime;

    // Set sprite's new position
    transform.position = position;
}

Vector3

Representation of 3D vectors and points.

Properties

  • back = Shorthand for Vector3(0, 0, -1)
  • down = Shorthand for Vector3(0, -1, 0)
  • forward = Shorthand for Vector3(0, 0, 1)
  • left = Shorthand for Vector3(-1, 0, 0)
  • right = Shorthand for Vector3(1, 0, 0)
  • up = Shorthand for Vector3(0, 1, 0)
  • zero = Shorthand for Vector3(0, 0, 0)
  • x = X-axis component of the vector
  • y = Y-axis component of the vector
  • z = Z-axis component of the vector

// Examples

// Set GameObject's Vector3 position to new y-axis position
public Vector3 cubePos;
public float y = 15;
cubePos = new Vector3(transform.position.x, y, transform.position.z);
transform.position = cubePos;

// Set rotate properties to a rotation speed along the y-axis -> Vector3.up
transform.Rotate (Vector3.up * rotationSpeed * Time.deltaTime, Space.World);

For more resources and class examples, check out the Unity Scripting API Docs.


Troubleshooting


Serialization Issues

On some devices, Unity does not serialize or add public variables automatically to the Inspector window. You can force the serialization of any variable by inserting the [SerializeField] on the line just above the variable you want to use in the Inspector window.

// Example

[SerializeField]
public GameObject player;

[SerializeField]
private int speed = 4;

For more resources, check out the Unity Docs.