You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
// Various examples of Input usage in UnityusingUnityEngine;usingSystem.Collections;publicclassInputExamples:MonoBehaviour{// These strings need to be set in the Inspector to match Input Manager entriespublicstringhoriAxis,vertAxis,jump;publicKeyCodekey1;publicVector2speed=newVector2(10f,5f);voidUpdate(){// 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 appliedDebug.Log("Vertical: "+Input.GetAxisRaw(vertAxis));// This is often multiplied by a number to create movementDebug.Log("Horizontal Modified: "+Input.GetAxis(horiAxis)*speed.x);// Key pressed downif(Input.GetKeyDown(KeyCode.T)){Debug.Log("Key T pressed");}// KeyCode can also be set in the Inspector as a variableif(Input.GetKeyUp(key1)){Debug.Log("Key Released");}// Run only once when button is pressedif(Input.GetButtonDown(jump)){Debug.Log("Jump");}}}
InstantiateExamples.cs
// Various Instantiate examples for UnityusingUnityEngine;usingSystem.Collections;publicclassInstantiateExamples:MonoBehaviour{// Set the object to be cloned in the Inspector.publicGameObjectprefab;// Set a target transform in the Inspector to clone prefab frompublicTransformspawnPoint;// Update is called once per framevoidUpdate(){// Basic cloningif(Input.GetButton("X")){// Pass the prefab as an argument and clone it at the spawnPoint // spawnPoint can be set to transform for cloning the prefab at the position of this objectInstantiate(prefab,spawnPoint);//Instantiate(prefab, transform);}// Advanced cloningif(Input.GetButtonDown("Fire")){// Overloaded method which can be positioned and rotatedGameObjectprefab1=Instantiate(prefab,transform.position,Quaternion.identity)asGameObject;// Make this prefab a child of the gameObject that spawned itprefab1.transform.parent=transform;// Destroying the prefab after a set amount of timeDestroy(prefab1,3f);// Accessing the cloned prefab's components. Note: The prefab needs a Rigidbody component for the next 2 lines to workRigidbodyprefabrigidbody=prefab1.GetComponent<Rigidbody>();prefabrigidbody.AddForce(Vector2.up*100f);}}}
FindExamples.cs
// Various ways of finding things in UnityusingUnityEngine;usingSystem.Collections;publicclassFindExamples:MonoBehaviour{// Example needs a Rigidbody component to workprivateRigidbodyrigidbody,otherrigidbody,childrigidbody;privateGameObjecthierarchyObject,childObject,taggedObject;voidStart(){// Find a component attached to this GameObjectrigidbody=GetComponent<Rigidbody>();// Find a GameObject in the Hierarchy, will check all GameObjects in the HierarchyhierarchyObject=GameObject.Find("Name Of Object");// Find a GameObject in the hierarchy based on tagtaggedObject=GameObject.FindWithTag("Player");// Can be combined to find a component on a GameObject in the Hierarchyotherrigidbody=GameObject.FindWithTag("Player").GetComponent<Rigidbody>();// Lowercase transform.Find can be used to search child GameObjects by namechildObject=transform.Find("Name Of Object").gameObject;// Can also be combined to find a component on a GameObject in the Hierarchychildrigidbody=transform.Find("Name Of Object").GetComponent<Rigidbody>();}}
EnableSetActiveExamples.cs
// Various ways of enabling/disabling a gameObject's components and activating/deactivating a gameObjectusingUnityEngine;usingSystem.Collections;publicclassEnableSetActiveExamples:MonoBehaviour{publicGameObjecttargetGameObject;privateCollidercollider;voidStart(){// 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 collider component attached to this gameObject. Note: Collider will work with any kind of collider component.collider=GetComponent<Collider>();// Disable or enable a component using a boolcollider.enabled=false;}// Update is called once per framevoidUpdate(){// Jump is space in Input Managerif(Input.GetButtonDown("Jump")){// Check if a gameObject is active in the scene with activeInHierarchyif(!targetGameObject.activeInHierarchy){targetGameObject.SetActive(true);}}// Fire is left ctrl in Input Managerif(Input.GetButtonDown("Fire")){// Check if a component is enabledif(!collider.enabled){collider.enabled=true;}}}}
CollisionExamples.cs
// Various collision examplesusingUnityEngine;usingSystem.Collections;publicclassCollisionExamples:MonoBehaviour{// Collisions/Triggers require a collider on both gameObjects and a rigidbody on at least one.voidOnCollisionEnter(Collisionother){// Do something when another collider touches this gameObject's colliderDebug.Log("Collided with something");// Conditional statements can be used to filter collisions/triggers// Checking for a known tag is one optionif(other.gameObject.CompareTag("tag1")){Debug.Log("tag1 collision");}// Checking for a known name is one optionelseif(other.gameObject.name.Equals("name1")){Debug.Log("name1 collision");}}// Is Trigger needs to be selected on one of the collidersvoidOnTriggerEnter(Colliderother){// Do something if another collider overlaps this gameObject's colliderDebug.Log("Triggered by something");}// Collision and Trigger also have stay eventvoidOnTriggerStay(Colliderother){// Do something while a collider is still overlapping with this gameObject's colliderDebug.Log("Still triggering");}// Collision and Trigger also have exit eventvoidOnCollisionExit(Collisionother){// Do something after a collider is no longer touching this gameObject's colliderDebug.Log("Collision ended");}}
AudioExamples.cs
// Various audio examples for UnityusingUnityEngine;usingSystem.Collections;publicclassAudioExamples:MonoBehaviour{// Attach an AudioSource component to this gameObjectprivateAudioSourceaudioSource;// Set an audioclip in the InspectorpublicAudioClipclip1;voidStart(){// Get the AudioSource componentaudioSource=GetComponent<AudioSource>();// Plays the AudioClip set in the AudioSource componentaudioSource.Play();}voidUpdate(){// AudioSource.Play() can also be paused or stopped// Check if audioSource is playing a clipif(audioSource.isPlaying){if(Input.GetButtonDown("P"))audioSource.Pause();elseif(Input.GetButtonDown("S"))audioSource.Stop();// Set the pitch and volume of the clips played by Audio Source. Volume range is 0~1audioSource.pitch=Random.Range(0.25f,2f);audioSource.volume=Random.Range(0.25f,1f);}// PlayOneShot can be used to play a short clip// Can't be used with Pause & Stopif(Input.GetButtonDown("Play")){audioSource.PlayOneShot(clip1);// You can give this an optional volume setting as well (0-1 range)//audioSource.PlayOneShot(clip1, 0.5f);}}}
IEnumeratorExamples.cs
// Various IEnumerator timer examples for UnityusingUnityEngine;usingSystem.Collections;publicclassIEnumeratorExamples:MonoBehaviour{// Flag for checking if a coroutine is runningprivateboolalreadyDelayed;// Necessary to stop a coroutineprivateIEnumeratorcoroutine;voidStart(){// Coroutines run in Start are only called once. No if statement + bool needed.StartCoroutine(LoopingTimer(7f));// Set to an IEnumeratorcoroutine=LoopingTimer(1f);StartCoroutine(coroutine);}voidUpdate(){// DelayTimerOneShotif(Input.GetButtonDown("PlayOneShot"))StartCoroutine(DelayTimerOneShot(1f));// Space bar is Jump in Input Managerif(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));if(Input.GetButtonDown("Fire")){// To stop a coroutineStopCoroutine(coroutine);Debug.Log("Stopped at "+Time.time);}}// Wait for an amount of time before doing somethingprivateIEnumeratorDelayTimerOneShot(floatdelayLength){yieldreturnnewWaitForSeconds(delayLength);Debug.Log("Delayed One Shot");}// Wait for an amount of time before doing somethingprivateIEnumeratorDelayTimerLatching(floatdelayLength){// Set the already delayed flag to signal that this coroutine is already runningalreadyDelayed=true;Debug.Log("Delayed Latch");yieldreturnnewWaitForSeconds(delayLength);Debug.Log("Delayed Latch Released");// Reset the already delayed flag so that this coroutine can be used once again.alreadyDelayed=false;}}
SceneManagementExamples.cs
// Various examples of scene managementusingUnityEngine;usingSystem.Collections;usingUnityEngine.SceneManagement;publicclassSceneManagementExamples:MonoBehaviour{// Name of new scene. Should be add the scene in build settings.publicstringscene;// Load the new scenepublicvoidLoadScene(stringnewScene){SceneManager.LoadScene(newScene);}// Reload the current scenepublicvoidReloadScene(){SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);}}
UIExamples.cs
// Various UI examplesusingUnityEngine;usingSystem.Collections;usingUnityEngine.UI;publicclassUIExamples:MonoBehaviour{// Set the target UI Text in the InspectorpublicTextuiText;// Set the target UI image in Inspector. UI Image must be "filled" typepublicImageuiImage;privateintuiNumber=5;voidUpdate(){if(Input.GetButtonDown("Jump")){// Basic usageuiText.text="CODEMAKER";// Fill amount is in a range from 0-1. EmptyuiImage.fillAmount=0;}elseif(Input.GetButtonDown("Fire1")){// Numbers must be converted to stringsuiText.text=uiNumber.ToString();// Larger ranges of number can be converted by dividing with the max valueuiImage.fillAmount=2.5f/uiNumber;}elseif(Input.GetButtonDown("Fire2")){// Numbers can be formatted to display a certain number of placesuiText.text=uiNumber.ToString("000");// FulluiImage.fillAmount=1;}}}