Last active
October 15, 2024 19:38
-
-
Save samsheffield/96608e465091069d15fdaea29457ec85 to your computer and use it in GitHub Desktop.
Unity C# Cheat Sheet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Unity C# Cheat Sheet | |
// I made these examples for students with prior exerience working with C# and Unity. | |
// Too much? Try Unity's very good tutorials to get up to speed: https://unity3d.com/learn/tutorials/topics/scripting |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Various audio examples for Unity | |
using UnityEngine; | |
using System.Collections; | |
public class AudioExamples : MonoBehaviour | |
{ | |
// Important: You need to have an AudioSource component attached to this gameObject | |
private AudioSource audioSource; | |
// Set an audioclip in the Inspector | |
public AudioClip clip1; | |
void Start() | |
{ | |
// Get the AudioSource component | |
audioSource = GetComponent<AudioSource>(); | |
// Plays the AudioClip set in the AudioSource component. Will be interrupted if the function is called again. | |
audioSource.Play(); | |
} | |
void Update() | |
{ | |
// AudioSource.Play() can also be paused or stopped. | |
// Check if audioSource is playing a clip. Jump is space and Fire1 is left ctrl. | |
if (audioSource.isPlaying) | |
{ | |
if (Input.GetButtonDown("Jump")) | |
{ | |
audioSource.Pause(); | |
} | |
else if (Input.GetButtonDown("Fire1")) | |
{ | |
audioSource.Stop(); | |
} | |
} | |
// PlayOneShot can be used to play a short clip. Will not be interrupted if the function is called again. | |
// Can't be used with Pause & Stop. Fire2 is left alt in the Input Manager. | |
if (Input.GetButtonDown("Fire2")) | |
{ | |
audioSource.PlayOneShot(clip1); | |
// You can give this an optional volume setting as well (0-1 range) | |
//audioSource.PlayOneShot(clip1, 0.5f); | |
} | |
// Fire3 is left shift | |
if (Input.GetButtonDown("Fire3")) | |
{ | |
// Set the pitch and volume of the clips played by Audio Source. Volume range is 0~1 | |
audioSource.pitch = Random.Range(0.25f, 2f); | |
audioSource.volume = Random.Range(0.25f, 1f); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Various 2D collision examples | |
using UnityEngine; | |
using System.Collections; | |
public class Collision2DExamples : MonoBehaviour | |
{ | |
// Collisions/Triggers require a collider component on both gameObjects and a rigidbody on at least one. | |
// Collision = physics. Trigger = overlap. | |
void OnCollisionEnter2D(Collision2D other) | |
{ | |
// Do something when another collider touches this gameObject's collider | |
Debug.Log("Collided with something"); | |
// Conditional statements can be used to filter collisions/triggers. Checking for a known tag is one option. Be sure to define tag in the Inspector or you will get an error. | |
if (other.gameObject.CompareTag("tag1")) | |
{ | |
Debug.Log("tag1 collision"); | |
} | |
else if (other.gameObject.CompareTag("tag2")) | |
{ | |
Debug.Log("tag2 collision"); | |
} | |
} | |
// Is Trigger needs to be selected on one of the colliders | |
void OnTriggerEnter2D(Collider2D other) | |
{ | |
// Do something if another collider overlaps this gameObject's collider | |
Debug.Log("Triggered by something"); | |
} | |
// Collision and Trigger also have exit and stay events | |
void OnCollisionExit2D(Collision2D other) | |
{ | |
// Do something after a collider is no longer touching this gameObject's collider | |
Debug.Log("Collision ended"); | |
} | |
void OnTriggerStay2D(Collider2D other) | |
{ | |
// Do something while a collider is still overlapping with this gameObject's collider | |
Debug.Log("Still triggering"); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Various ways of enabling/disabling a gameObject's components and activating/deactivating a gameObject. | |
using UnityEngine; | |
using System.Collections; | |
public class EnableSetActiveExamples : MonoBehaviour | |
{ | |
public GameObject targetGameObject; | |
private Collider2D coll2D; | |
void Start() | |
{ | |
// SetActive can switch a gameObject on or off in the Hierarchy. Once deactivated, its components will no longer run until reactivated. | |
targetGameObject.SetActive(false); | |
// Get a collider2D component attached to this gameObject. Note: Collider2D will work with any kind of 2D collider component. | |
coll2D = GetComponent<Collider2D>(); | |
// Disable or enable a component using a bool | |
coll2D.enabled = false; | |
} | |
// Update is called once per frame | |
void Update() | |
{ | |
// Jump is space in Input Manager | |
if (Input.GetButtonDown("Jump")) | |
{ | |
// Check if a gameObject is active in the scene with activeInHierarchy. Reminder: The ! is shorthand for == false. If the gameObject is inactive, activate it | |
if (!targetGameObject.activeInHierarchy) | |
{ | |
targetGameObject.SetActive(true); | |
} | |
} | |
// Fire1 is left ctrl in Input Manager | |
if (Input.GetButtonDown("Fire1")) | |
{ | |
// Check if a component is enabled. Reminder: The ! is shorthand for == false. | |
if (!coll2D.enabled) | |
{ | |
coll2D.enabled = true; | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Various ways of finding things in Unity | |
using UnityEngine; | |
using System.Collections; | |
public class FindExamples : MonoBehaviour | |
{ | |
// Example needs a Rigidbody2D component to work | |
private Rigidbody2D rb2D, otherRb2D, childRb2D; | |
private GameObject hierarchyObject, childObject, taggedObject; | |
void Start() | |
{ | |
// Find a component attached to this GameObject | |
rb2D = GetComponent<Rigidbody2D>(); | |
// Find a GameObject in the Hierarchy. NOTE: This will check all GameObjects in the Hierarchy! Proceed with caution... | |
hierarchyObject = GameObject.Find("Name Of Object"); | |
// Find a GameObject in the hierarchy based on tag. NOTE: Fast than finding by name since it only needs to check GameObjects with the matching tag. | |
taggedObject = GameObject.FindWithTag("Player"); | |
// Can be combined to find a component on a GameObject in the Hierarchy | |
otherRb2D = GameObject.FindWithTag("Player").GetComponent<Rigidbody2D>(); | |
// Lowercase transform.Find can be used to search child GameObjects by name | |
childObject = transform.Find("Name Of Object").gameObject; | |
// Can also be combined | |
childRb2D = transform.Find("Name Of Object").GetComponent<Rigidbody2D>(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Various IEnumerator timer examples for Unity | |
using UnityEngine; | |
using System.Collections; | |
public class IEnumeratorExamples : MonoBehaviour | |
{ | |
// Flag for checking if a coroutine is running | |
private bool alreadyDelayed; | |
// Necessary to stop a coroutine | |
private IEnumerator coroutine; | |
void Start() | |
{ | |
// Coroutines run in Start are only called once. No if statement + bool needed. | |
StartCoroutine(LoopingTimer(7f)); | |
// Set to an IEnumerator | |
coroutine = LoopingTimer(1f); | |
StartCoroutine(coroutine); | |
} | |
void Update() | |
{ | |
// Left ctrl key is Fire1 in Input Manager | |
if (Input.GetButtonDown("Fire1")) | |
{ | |
StartCoroutine(DelayTimerOneShot(1f)); | |
} | |
// Space bar is Jump in Input Manager | |
if (Input.GetButtonDown("Jump")) | |
{ | |
// This if statement ensures that a coroutine can't be run again if it is already running. | |
if (!alreadyDelayed) | |
{ | |
StartCoroutine(DelayTimerLatching(3f)); | |
} | |
} | |
// Left alt is Fire2 in Input Manager. | |
if (Input.GetButtonDown("Fire2")) | |
{ | |
// To stop a coroutine... | |
StopCoroutine(coroutine); | |
Debug.Log("Stopped at " + Time.time); | |
} | |
} | |
// Wait for an amount of time before doing something (one shot behavior) | |
private IEnumerator DelayTimerOneShot(float delayLength) | |
{ | |
yield return new WaitForSeconds(delayLength); | |
// Do something | |
Debug.Log("Delayed One Shot"); | |
} | |
// Wait for an amount of time before doing something (latching behavior) | |
private IEnumerator DelayTimerLatching(float delayLength) | |
{ | |
// Set the already delayed flag to signal that this coroutine is already running | |
alreadyDelayed = true; | |
// Do something | |
Debug.Log("Delayed Latch"); | |
yield return new WaitForSeconds(delayLength); | |
// Do something | |
Debug.Log("Delayed Latch Released"); | |
// Reset the already delayed flag so that this coroutine can be used once again. | |
alreadyDelayed = false; | |
} | |
// Sequence of delays | |
private IEnumerator DelayTimerSequence(float delayLength1, float delayLength2) | |
{ | |
alreadyDelayed = true; | |
yield return new WaitForSeconds(delayLength1); | |
// Do first thing | |
Debug.Log("First Delay"); | |
yield return new WaitForSeconds(delayLength2); | |
// Do second thing | |
Debug.Log("Second Delay"); | |
alreadyDelayed = false; | |
} | |
// This creates an endless loop | |
private IEnumerator LoopingTimer(float loopInterval) | |
{ | |
while (true) | |
{ | |
// Do something | |
Debug.Log("Repeat"); | |
yield return new WaitForSeconds(loopInterval); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Various examples of Input usage in Unity | |
using UnityEngine; | |
using System.Collections; | |
public class InputExamples : MonoBehaviour | |
{ | |
// These strings need to be set in the Inspector to match Input Manager entries | |
public string horiAxis, vertAxis, jump, button1, button2; | |
public KeyCode key1; | |
public Vector2 speed = new Vector2(10f, 5f); | |
void Update() | |
{ | |
// Run only once when button is pressed | |
if (Input.GetButtonDown(jump)) | |
{ | |
Debug.Log("Jump"); | |
} | |
// Keep running while button is held down | |
if (Input.GetButton(button1)) | |
{ | |
Debug.Log("Fire1"); | |
} | |
// Run only once when the button is released | |
if (Input.GetButtonUp(button2)) | |
{ | |
Debug.Log("Fire2"); | |
} | |
// Input.GetAxis will return a number between -1 and 1, with smoothing applied (adjust Sensitivity in Input Manager) | |
Debug.Log("Horizontal: " + Input.GetAxis(horiAxis)); | |
// Input.GetAxisRaw will return a number between -1 and 1, without Sensitivity smoothing applied | |
Debug.Log("Vertical: " + Input.GetAxisRaw(vertAxis)); | |
// This is often multiplied by a number to create movement | |
Debug.Log("Horizontal Modified: " + Input.GetAxis(horiAxis) * speed.x); | |
// Key pressed down | |
if (Input.GetKeyDown(KeyCode.T)) | |
{ | |
Debug.Log("Key T pressed"); | |
} | |
// Key held down | |
if (Input.GetKey(KeyCode.Y)) | |
{ | |
Debug.Log("Key A pressed"); | |
} | |
// KeyCode can also be set in the Inspector as a variable | |
if (Input.GetKeyUp(key1)) | |
{ | |
Debug.Log("Key released"); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Various Instantiate examples for Unity | |
using UnityEngine; | |
using System.Collections; | |
public class InstantiateExamples : MonoBehaviour | |
{ | |
// Set the object to be cloned in the Inspector. Be sure to use a Prefab from Project NOT Scene! | |
public GameObject prefab; | |
// Set a target transform in the Inspector to clone prefab from | |
public Transform spawnPoint; | |
// Update is called once per frame | |
void Update() | |
{ | |
// Basic cloning | |
if (Input.GetButtonDown("Jump")) | |
{ | |
// Pass the prefab as an argument and clone it at the transform of this gameObject. | |
Instantiate(prefab, transform); | |
// Second argument could be set to different transform, if there is another place the prefab should be cloned. | |
//Instantiate(prefab, spawnPoint); | |
} | |
// Advanced cloning | |
if (Input.GetButtonDown("Fire1")) | |
{ | |
// Overloaded method which can be positioned and rotated. | |
GameObject p = Instantiate(prefab, transform.position, Quaternion.identity) as GameObject; | |
// Make this clone a child of the gameObject that spawned it | |
p.transform.parent = transform; | |
// This approach allows you to further manipulate the cloned prefab in this script. Such as... | |
// Destroying the clone after a set amount of time | |
Destroy(p, 3f); | |
// Accessing the cloned prefab's components. Note: The prefab needs a Rigidbody2D component for the next 2 lines to work. | |
Rigidbody2D pRB2D = p.GetComponent<Rigidbody2D>(); | |
pRB2D.AddForce(Vector2.up * 100f); | |
} | |
// Clone prefab at specified transform | |
if (Input.GetButtonDown("Fire2")) | |
{ | |
GameObject p = Instantiate(prefab, spawnPoint.position, Quaternion.identity) as GameObject; | |
p.transform.parent = transform; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Various examples of scene management for Unity 5+ | |
using UnityEngine; | |
using System.Collections; | |
// Needed in Unity 5+ | |
using UnityEngine.SceneManagement; | |
public class SceneManagementExamples : MonoBehaviour | |
{ | |
// Name of new scene. Don't forget to add to build settings! | |
public string scene; | |
// Load the new scene | |
public void LoadScene(string newScene) | |
{ | |
SceneManager.LoadScene(newScene); | |
} | |
// Reload the current scene | |
public void ReloadScene() | |
{ | |
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Various UI examples for Unity 5+ | |
using UnityEngine; | |
using System.Collections; | |
// Needed fro UI in Unity 5+ | |
using UnityEngine.UI; | |
public class UIExamples : MonoBehaviour | |
{ | |
// Set the target UI Text in the Inspector | |
public Text uiText; | |
// Set the target UI image in Inspector. UI Image must be "filled" type | |
public Image uiImage; | |
private int uiNumber = 7; | |
void Update() | |
{ | |
if (Input.GetButtonDown("Jump")) | |
{ | |
// Basic usage | |
uiText.text = "HELLO"; | |
// Fill amount is in a range from 0-1. Empty | |
uiImage.fillAmount = 0; | |
} | |
else if (Input.GetButtonDown("Fire1")) | |
{ | |
// Numbers must be converted to strings | |
uiText.text = uiNumber.ToString(); | |
// Larger ranges of number can be converted by dividing with the max value. Halfway | |
uiImage.fillAmount = 3.5f/uiNumber; | |
} | |
else if (Input.GetButtonDown("Fire2")) | |
{ | |
// Numbers can be formatted to display a certain number of places | |
uiText.text = uiNumber.ToString("000"); | |
// Full | |
uiImage.fillAmount = 1; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This great thank you mate.