Showing Progress While Loading Scene | Unity Game Engine
SceneLoader.cs
using System.Collections; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; public class SceneLoader : MonoBehaviour { public GameObject LoaderUI; public Slider progressSlider; public void LoadScene(int index) { StartCoroutine(LoadScene_Coroutine(index)); } public IEnumerator LoadScene_Coroutine(int index) { progressSlider.value = 0; LoaderUI.SetActive(true); AsyncOperation asyncOperation = SceneManager.LoadSceneAsync(1); asyncOperation.allowSceneActivation = false; float progress = 0; while (!asyncOperation.isDone) { progress = Mathf.MoveTowards(progress, asyncOperation.progress, Time.deltaTime); progressSlider.value = progress; if (progress >= 0.9f) { progressSlider.value = 1; asyncOperation.allowSceneActivation = true; } yield return null; } } }
Player Movement using Character Controller(Move, Turn, Jump, Fall) | Unity Game Engine
PlayerController.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; [RequireComponent(typeof(CharacterController))] public class PlayerController : MonoBehaviour { public float speed = 3; public float rotationSpeed = 90; public float gravity = -20f; public float jumpSpeed = 15; CharacterController characterController; Vector3 moveVelocity; Vector3 turnVelocity; void Awake() { characterController = GetComponent<CharacterController>(); } void Update() { var hInput = Input.GetAxis("Horizontal"); var vInput = Input.GetAxis("Vertical"); if(characterController.isGrounded) { moveVelocity = transform.forward * speed * vInput; turnVelocity = transform.up * rotationSpeed * hInput; if(Input.GetButtonDown("Jump")) { moveVelocity.y = jumpSpeed; } } //Adding gravity moveVelocity.y += gravity * Time.deltaTime; characterController.Move(moveVelocity * Time.deltaTime); transform.Rotate(turnVelocity * Time.deltaTime); } }
Shooting Laser using Raycast and LineRenderer | Unity Game Engine
RaycastGun.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; [RequireComponent(typeof(LineRenderer))] public class RaycastGun : MonoBehaviour { public Camera playerCamera; public Transform laserOrigin; public float gunRange = 50f; public float fireRate = 0.2f; public float laserDuration = 0.05f; LineRenderer laserLine; float fireTimer; void Awake() { laserLine = GetComponent<LineRenderer>(); } void Update() { fireTimer += Time.deltaTime; if(Input.GetButtonDown("Fire1") && fireTimer > fireRate) { fireTimer = 0; laserLine.SetPosition(0, laserOrigin.position); Vector3 rayOrigin = playerCamera.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, 0)); RaycastHit hit; if(Physics.Raycast(rayOrigin, playerCamera.transform.forward, out hit, gunRange)) { laserLine.SetPosition(1, hit.point); Destroy(hit.transform.gameObject); } else { laserLine.SetPosition(1, rayOrigin + (playerCamera.transform.forward * gunRange)); } StartCoroutine(ShootLaser()); } } IEnumerator ShootLaser() { laserLine.enabled = true; yield return new WaitForSeconds(laserDuration); laserLine.enabled = false; } }
Launching Projectiles | 3D | Unity Game Engine
LaunchProjectile.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class LaunchProjectile : MonoBehaviour { public Transform launchPoint; public GameObject projectile; public float launchVelocity = 10f; void Update() { if(Input.GetButtonDown("Fire1")) { var _projectile = Instantiate(projectile, launchPoint.position, launchPoint.rotation); _projectile.GetComponent<Rigidbody>().velocity = launchPoint.up * launchVelocity; } } }
Projectile.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Projectile : MonoBehaviour { public float life = 5f; void Awake() { Destroy(gameObject, life); } }
2D Tank Movement and Shooting | Unity Game Engine
Tank2D.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Tank2D : MonoBehaviour { public Transform bulletSpawnPoint; public GameObject bulletPrefab; public float bulletSpeed = 10; public float moveSpeed = 2; void Update() { Movement(); Shooting(); } void Movement() { float h = Input.GetAxisRaw("Horizontal"); float v = Input.GetAxisRaw("Vertical"); if (h != 0) { transform.position += new Vector3(h * moveSpeed * Time.deltaTime, 0, 0); transform.rotation = Quaternion.Euler(0, 0, -90 * h); } else if (v != 0) { transform.position += new Vector3(0, v * moveSpeed * Time.deltaTime, 0); transform.rotation = Quaternion.Euler(0, 0, 90 - 90 * v); } } void Shooting() { if(Input.GetKeyDown(KeyCode.Space)) { var bullet = Instantiate(bulletPrefab, bulletSpawnPoint.position, bulletSpawnPoint.rotation); bullet.GetComponent<Rigidbody2D>().velocity = bulletSpawnPoint.up * bulletSpeed; } } }
Bullet.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Bullet : MonoBehaviour { public float life = 3; void Awake() { Destroy(gameObject, life); } void OnCollisionEnter2D(Collision2D collision) { Destroy(collision.gameObject); Destroy(gameObject); } }
Simple Shooting | 3D | Bullets | Unity Game Engine
Gun.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Gun : MonoBehaviour { public Transform bulletSpawnPoint; public GameObject bulletPrefab; public float bulletSpeed = 10; void Update() { if(Input.GetKeyDown(KeyCode.Space)) { var bullet = Instantiate(bulletPrefab, bulletSpawnPoint.position, bulletSpawnPoint.rotation); bullet.GetComponent<Rigidbody>().velocity = bulletSpawnPoint.forward * bulletSpeed; } } }
Bullet.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Bullet : MonoBehaviour { public float life = 3; void Awake() { Destroy(gameObject, life); } void OnCollisionEnter(Collision collision) { Destroy(collision.gameObject); Destroy(gameObject); } }
Simple Shooting | 2D | Bullets | Unity Game Engine
Gun2D.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Gun2D : MonoBehaviour { public Transform bulletSpawnPoint; public GameObject bulletPrefab; public float bulletSpeed = 10; void Update() { if(Input.GetKeyDown(KeyCode.Space)) { var bullet = Instantiate(bulletPrefab, bulletSpawnPoint.position, bulletSpawnPoint.rotation); bullet.GetComponent<Rigidbody2D>().velocity = bulletSpawnPoint.up * bulletSpeed; } } }
Bullet.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Bullet : MonoBehaviour { public float life = 3; void Awake() { Destroy(gameObject, life); } void OnCollisionEnter2D(Collision2D collision) { Destroy(collision.gameObject); Destroy(gameObject); } }
Drag & Drop | Screen-Space UI Elements | Unity Game Engine
DragDropUI.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; public class DragDropUI : MonoBehaviour, IPointerDownHandler, IDragHandler, IPointerUpHandler { Vector3 offset; CanvasGroup canvasGroup; public string destinationTag = "DropArea"; void Awake() { if (gameObject.GetComponent<CanvasGroup>() == null) gameObject.AddComponent<CanvasGroup>(); canvasGroup = gameObject.GetComponent<CanvasGroup>(); } public void OnDrag(PointerEventData eventData) { transform.position = Input.mousePosition + offset; } public void OnPointerDown(PointerEventData eventData) { offset = transform.position - Input.mousePosition; canvasGroup.alpha = 0.5f; canvasGroup.blocksRaycasts = false; } public void OnPointerUp(PointerEventData eventData) { RaycastResult raycastResult = eventData.pointerCurrentRaycast; if(raycastResult.gameObject?.tag == destinationTag) { transform.position = raycastResult.gameObject.transform.position; } canvasGroup.alpha = 1; canvasGroup.blocksRaycasts = true; } }
Drag & Drop | World-Space 3D Objects | Unity Game Engine
DragDrop.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class DragDrop : MonoBehaviour { Vector3 offset; public string destinationTag = "DropArea"; void OnMouseDown() { offset = transform.position - MouseWorldPosition(); transform.GetComponent<Collider>().enabled = false; } void OnMouseDrag() { transform.position = MouseWorldPosition() + offset; } void OnMouseUp() { var rayOrigin = Camera.main.transform.position; var rayDirection = MouseWorldPosition() - Camera.main.transform.position; RaycastHit hitInfo; if(Physics.Raycast(rayOrigin, rayDirection, out hitInfo)) { if(hitInfo.transform.tag == destinationTag) { transform.position = hitInfo.transform.position; } } transform.GetComponent<Collider>().enabled = true; } Vector3 MouseWorldPosition() { var mouseScreenPos = Input.mousePosition; mouseScreenPos.z = Camera.main.WorldToScreenPoint(transform.position).z; return Camera.main.ScreenToWorldPoint(mouseScreenPos); } }
Character movement via on-screen Joystick controller input | Rigidbody | Unity Game Engine
JoystickController.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; public class JoystickController : MonoBehaviour, IPointerDownHandler, IDragHandler, IPointerUpHandler { [SerializeField] private float maxDisplacement = 200; Vector2 startPos; Transform handle; public static float Horizontal = 0, Vertical = 0; void Start() { handle = transform.GetChild(0); startPos = handle.position; } void UpdateHandlePosition(Vector2 pos) { var delta = pos - startPos; delta = Vector2.ClampMagnitude(delta, maxDisplacement); handle.position = startPos + delta; Horizontal = delta.x / maxDisplacement; Vertical = delta.y / maxDisplacement; } public void OnPointerDown(PointerEventData eventData) { UpdateHandlePosition(eventData.position); } public void OnDrag(PointerEventData eventData) { UpdateHandlePosition(eventData.position); } public void OnPointerUp(PointerEventData eventData) { UpdateHandlePosition(startPos); } }
JoystickMove.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; [RequireComponent(typeof(Rigidbody))] public class JoystickMove : MonoBehaviour { public float speed = 5; Rigidbody rigidBody; void Awake() { rigidBody = GetComponent<Rigidbody>(); } void FixedUpdate() { float inputH = JoystickController.Horizontal; float inputV = JoystickController.Vertical; rigidBody.velocity = new Vector3(inputH * speed, rigidBody.velocity.y, inputV * speed); } }
Character movement via on-screen touch controller input | Rigidbody | Unity Game Engine
TouchController.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; public class TouchController : MonoBehaviour { public static float Horizontal = 0, Vertical = 0; void Awake() { SetupButton(transform.Find("up").gameObject, Vector2.up); SetupButton(transform.Find("down").gameObject, Vector2.down); SetupButton(transform.Find("left").gameObject, Vector2.left); SetupButton(transform.Find("right").gameObject, Vector2.right); } void SetupButton(GameObject buttonObject, Vector2 position) { EventTrigger eventTrigger = buttonObject.AddComponent<EventTrigger>(); var pointerDown = new EventTrigger.Entry(); pointerDown.eventID = EventTriggerType.PointerDown; pointerDown.callback.AddListener((e) => UpdateAxisValue(position)); eventTrigger.triggers.Add(pointerDown); var pointerUp = new EventTrigger.Entry(); pointerUp.eventID = EventTriggerType.PointerUp; pointerUp.callback.AddListener((e) => UpdateAxisValue(position, reset: true)); eventTrigger.triggers.Add(pointerUp); } void UpdateAxisValue(Vector2 position, bool reset = false) { if (position.x == 0) Vertical = reset ? 0 : position.y; else Horizontal = reset ? 0 : position.x; } }
TouchMove.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; [RequireComponent(typeof(Rigidbody))] public class TouchMove : MonoBehaviour { public float speed = 5; Rigidbody rigidBody; void Awake() { rigidBody = GetComponent<Rigidbody>(); } void FixedUpdate() { float inputH = TouchController.Horizontal; float inputV = TouchController.Vertical; rigidBody.velocity = new Vector3(inputH * speed, rigidBody.velocity.y, inputV * speed); } }
Character movement via keyboard/controller input | Rigidbody | Unity Game Engine
Move.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; [RequireComponent(typeof(Rigidbody))] public class Move : MonoBehaviour { public float speed = 5; Rigidbody rigidBody; void Awake() { rigidBody = GetComponent<Rigidbody>(); } void FixedUpdate() { float inputH = Input.GetAxis("Horizontal"); float inputV = Input.GetAxis("Vertical"); rigidBody.velocity = new Vector3(inputH * speed, rigidBody.velocity.y, inputV * speed); } }
Double Jump | Rigidbody | Unity Game Engine
DoubleJump.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; [RequireComponent(typeof(Rigidbody))] public class DoubleJump : MonoBehaviour { public float jumpForce = 5; public float groundDistance = 0.5f; Rigidbody rigidBody; bool canDoubleJump; void Awake() { rigidBody = GetComponent<Rigidbody>(); } bool IsGrounded() { return Physics.Raycast(transform.position, Vector3.down, groundDistance); } void Update() { if(Input.GetMouseButtonDown(0)) { if(IsGrounded()) { rigidBody.velocity = Vector3.up * jumpForce; canDoubleJump = true; } else if(canDoubleJump) { rigidBody.velocity = Vector3.up * jumpForce; canDoubleJump = false; } } } }
Single Jump | Rigidbody | Unity Game Engine
SingleJump.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; [RequireComponent(typeof(Rigidbody))] public class SingleJump : MonoBehaviour { public float jumpForce = 5; public float groundDistance = 0.5f; Rigidbody rigidBody; void Awake() { rigidBody = GetComponent<Rigidbody>(); } bool IsGrounded() { return Physics.Raycast(transform.position, Vector3.down, groundDistance); } void Update() { if(Input.GetMouseButtonDown(0) && IsGrounded()) { rigidBody.velocity = Vector3.up * jumpForce; } } }
Continuous Jump | Rigidbody | Unity Game Engine
Jump.cs
using UnityEngine; [RequireComponent(typeof(Rigidbody))] public class Jump : MonoBehaviour { public float jumpForce = 4; public float jumpInterval = 0.25f; Rigidbody rigidBody; float jumpTimer; void Awake() { rigidBody = GetComponent<Rigidbody>(); } void Update() { jumpTimer += Time.deltaTime; if (Input.GetMouseButtonDown(0)) { if (jumpTimer > jumpInterval) { jumpTimer = 0; rigidBody.velocity = Vector3.up * jumpForce; } } } }
Display a number counting towards the target number | Unity Game Engine
Count2Target.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; [RequireComponent(typeof(Text))] public class Count2Target : MonoBehaviour { public float countDuration = 1; Text numberText; float currentValue = 0, targetValue = 0; Coroutine _C2T; void Awake() { numberText = GetComponent<Text>(); } void Start() { currentValue = float.Parse(numberText.text); targetValue = currentValue; } IEnumerator CountTo(float targetValue) { var rate = Mathf.Abs(targetValue - currentValue) / countDuration; while(currentValue != targetValue) { currentValue = Mathf.MoveTowards(currentValue, targetValue, rate * Time.deltaTime); numberText.text = ((int)currentValue).ToString(); yield return null; } } public void AddValue(float value) { targetValue += value; if (_C2T != null) StopCoroutine(_C2T); _C2T = StartCoroutine(CountTo(targetValue)); } public void SetTarget(float target) { targetValue = target; if (_C2T != null) StopCoroutine(_C2T); _C2T = StartCoroutine(CountTo(targetValue)); } }
Get/Post REST API Data using HttpClient | Unity Game Engine
GetMethod.cs
using UnityEngine; using UnityEngine.UI; using System.Net.Http; public class GetMethod : MonoBehaviour { InputField outputArea; void Start() { outputArea = GameObject.Find("OutputArea").GetComponent<InputField>(); GameObject.Find("GetButton").GetComponent<Button>().onClick.AddListener(GetData); } async void GetData() { outputArea.text = "Loading..."; string url = "https://my-json-server.typicode.com/typicode/demo/posts"; using(var httpClient = new HttpClient()) { var response = await httpClient.GetAsync(url); if (response.IsSuccessStatusCode) outputArea.text = await response.Content.ReadAsStringAsync(); else outputArea.text = response.ReasonPhrase; } } }
PostMethod.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using System.Net.Http; public class PostMethod : MonoBehaviour { InputField outputArea; void Start() { outputArea = GameObject.Find("OutputArea").GetComponent<InputField>(); GameObject.Find("PostButton").GetComponent<Button>().onClick.AddListener(PostData); } async void PostData() { outputArea.text = "Loading..."; string url = "https://my-json-server.typicode.com/typicode/demo/posts"; var postData = new Dictionary<string, string>(); postData["title"] = "test data"; using(var httpClient = new HttpClient()) { var response = await httpClient.PostAsync(url, new FormUrlEncodedContent(postData)); if (response.IsSuccessStatusCode) outputArea.text = await response.Content.ReadAsStringAsync(); else outputArea.text = response.ReasonPhrase; } } }
Creating Image Blink effect by Changing Color | UI | Color Lerp | Unity Game Engine
ImageBlinkEffect.cs
using UnityEngine; using UnityEngine.UI; public class ImageBlinkEffect : MonoBehaviour { public Color startColor = Color.green; public Color endColor = Color.black; [Range(0,10)] public float speed = 1; Image imgComp; void Awake() { imgComp = GetComponent<Image>(); } void Update() { imgComp.color = Color.Lerp(startColor, endColor, Mathf.PingPong(Time.time * speed, 1)); } }
Creating Object Blink effect by Changing Color| 2D/3D Object | Color Lerp | Unity Game Engine
BlinkEffect.cs
using UnityEngine; public class BlinkEffect : MonoBehaviour { public Color startColor = Color.green; public Color endColor = Color.black; [Range(0,10)] public float speed = 1; Renderer ren; void Awake() { ren = GetComponent<Renderer>(); } void Update() { ren.material.color = Color.Lerp(startColor, endColor, Mathf.PingPong(Time.time * speed, 1)); } }
Getting a Random Value from a List of Weighted Values | Unity Game Engine
WeightedValue.cs
using System; [Serializable] public class WeightedValue { public string value; public int weight; }
PrintRandomValue.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PrintRandomValue : MonoBehaviour { public List<WeightedValue> weightedValues; void Update() { if(Input.GetMouseButtonDown(0)) { string randomValue = GetRandomValue(weightedValues); Debug.Log(randomValue ?? "No entries found"); } } string GetRandomValue(List<WeightedValue> weightedValueList) { string output = null; //Getting a random weight value var totalWeight = 0; foreach (var entry in weightedValueList) { totalWeight += entry.weight; } var rndWeightValue = Random.Range(1, totalWeight + 1); //Checking where random weight value falls var processedWeight = 0; foreach (var entry in weightedValueList) { processedWeight += entry.weight; if(rndWeightValue <= processedWeight) { output = entry.value; break; } } return output; } }
Binding Slider's Value to a Text Component | Using onValueChanged event | Unity Game Engine
SliderValueText.cs
using UnityEngine; using UnityEngine.UI; public class SliderValueText : MonoBehaviour { private Slider slider; private Text textComp; void Awake() { slider = GetComponentInParent<Slider>(); textComp = GetComponent<Text>(); } void Start() { UpdateText(slider.value); slider.onValueChanged.AddListener(UpdateText); } void UpdateText(float val) { //textComp.text = slider.value.ToString(); textComp.text = val.ToString(); } }
Changing Dropdown options at Runtime | Unity Game Engine
DropdownOperations.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class DropdownOperations : MonoBehaviour { private Dropdown dropdown; void Awake() { dropdown = GetComponent<Dropdown>(); } public void LoadFruitOptions() { dropdown.ClearOptions(); var option1 = new Dropdown.OptionData("Apple"); dropdown.options.Add(option1); var option2 = new Dropdown.OptionData("Mango"); dropdown.options.Add(option2); dropdown.RefreshShownValue(); } public void LoadDrinkOptions() { dropdown.ClearOptions(); var option1 = new Dropdown.OptionData("Tea"); dropdown.options.Add(option1); var option2 = new Dropdown.OptionData("Coffee"); dropdown.options.Add(option2); dropdown.RefreshShownValue(); } }
Feed REST API Data to Unity UI Components | HttpClient | Unity Game Engine
WeaponsData.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; using System; [Serializable] public class WeaponsData { public List<Weapon> Weapons; } [Serializable] public class Stats { public int Attack; public int Defence; public int Speed; } [Serializable] public class Weapon { public string Name; public Stats Stats; }
GetWeaponsData.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using System.Net.Http; public class GetWeaponsData : MonoBehaviour { public Dropdown NamesDropDown; public Slider AttackSlider; public Slider DefenceSlider; public Slider SpeedSlider; WeaponsData weaponsData = null; async void Awake() { string url = "https://hostspace.github.io/mockapi/weapons.json"; using(var httpClient = new HttpClient()) { var response = await httpClient.GetAsync(url); if (response.IsSuccessStatusCode) { string json = await response.Content.ReadAsStringAsync(); weaponsData = JsonUtility.FromJson<WeaponsData>(json); } else Debug.LogError(response.ReasonPhrase); } if(weaponsData != null && weaponsData.Weapons.Count > 0) { NamesDropDown.options.Clear(); foreach (var weapon in weaponsData.Weapons) { NamesDropDown.options.Add(new Dropdown.OptionData(weapon.Name)); } NamesDropDown.value = 0; NamesDropDown.onValueChanged.AddListener(WeaponSelectEvent); WeaponSelectEvent(0); } } void WeaponSelectEvent(int index) { var stats = weaponsData.Weapons[index].Stats; AttackSlider.value = stats.Attack; DefenceSlider.value = stats.Defence; SpeedSlider.value = stats.Speed; } }
Feed REST API Data to Unity UI Components | UnityWebRequest | Unity Game Engine
WeaponsData.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; using System; [Serializable] public class WeaponsData { public List<Weapon> Weapons; } [Serializable] public class Stats { public int Attack; public int Defence; public int Speed; } [Serializable] public class Weapon { public string Name; public Stats Stats; }
GetWeaponsData.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.Networking; public class GetWeaponsData : MonoBehaviour { public Dropdown NamesDropDown; public Slider AttackSlider; public Slider DefenceSlider; public Slider SpeedSlider; WeaponsData weaponsData = null; void Awake() { StartCoroutine(GetData()); } IEnumerator GetData() { string url = "https://hostspace.github.io/mockapi/weapons.json"; using(var request = UnityWebRequest.Get(url)) { yield return request.SendWebRequest(); if (request.isHttpError || request.isNetworkError) Debug.LogError(request.error); else { string json = request.downloadHandler.text; weaponsData = JsonUtility.FromJson<WeaponsData>(json); } } if(weaponsData != null && weaponsData.Weapons.Count>0) { NamesDropDown.options.Clear(); foreach (var weapon in weaponsData.Weapons) { NamesDropDown.options.Add(new Dropdown.OptionData(weapon.Name)); } NamesDropDown.value = 0; NamesDropDown.onValueChanged.AddListener(WeaponSelectEvent); WeaponSelectEvent(0); } } void WeaponSelectEvent(int index) { var stats = weaponsData.Weapons[index].Stats; AttackSlider.value = stats.Attack; DefenceSlider.value = stats.Defence; SpeedSlider.value = stats.Speed; } }
Spawning Object at Mouse Position in Unity Game Engine
Spawner.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Spawner : MonoBehaviour { public GameObject Cube; void Update() { if(Input.GetMouseButtonDown(0)) { Vector3 mousePos = Input.mousePosition; mousePos.z = 10; Vector3 worldPosition = Camera.main.ScreenToWorldPoint(mousePos); Instantiate(Cube, worldPosition, Quaternion.identity); } } }
Spawning Objects in Unity Game Engine
Spawner.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Spawner : MonoBehaviour { public GameObject Sphere; void Update() { if(Input.GetMouseButtonDown(0)) { Instantiate(Sphere, transform.position, transform.rotation); } } }
Scriptable Objects Quick Demo in Unity Game Engine
PlayerData.cs
using UnityEngine; [CreateAssetMenu(menuName ="Player Data", fileName ="New Player Data")] public class PlayerData : ScriptableObject { public string playerName; public string playerClass; public Color playerColor; }
PlayerDisplay.cs
using UnityEngine; public class PlayerDisplay : MonoBehaviour { public PlayerData playerData; void Start() { transform.GetChild(0).GetComponent<TextMesh>().text = $"Name : {playerData.playerName}"; transform.GetChild(1).GetComponent<TextMesh>().text = $"Class : {playerData.playerClass}"; gameObject.GetComponent<Renderer>().material.color = playerData.playerColor; } }
Getting Unique Random Elements from a List in Unity Game Engine
PrintUniqueRandomElements.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PrintUniqueRandomElements : MonoBehaviour { List<int> list = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; List<T> GetUniqueRandomElements<T>(List<T> inputList, int count) { List<T> inputListClone = new List<T>(inputList); Shuffle(inputListClone); return inputListClone.GetRange(0, count); } void Shuffle<T>(List<T> inputList) { for (int i = 0; i < inputList.Count - 1; i++) { T temp = inputList[i]; int rand = Random.Range(i, inputList.Count); inputList[i] = inputList[rand]; inputList[rand] = temp; } } void Update() { if(Input.GetMouseButtonDown(0)) { var uniqueRandomList = GetUniqueRandomElements(list, 4); Debug.Log("All elements => " + string.Join(", ", list)); Debug.Log("Unique random elements => " + string.Join(", ", uniqueRandomList)); Debug.Log("*************************************************************"); } } }
Shuffling Elements of a List in Unity Game Engine
PrintShuffledList.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PrintShuffledList : MonoBehaviour { List<int> list = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; void Shuffle<T>(List<T> inputList) { for (int i = 0; i < inputList.Count - 1; i++) { T temp = inputList[i]; int rand = Random.Range(i, inputList.Count); inputList[i] = inputList[rand]; inputList[rand] = temp; } } void Update() { if(Input.GetMouseButtonDown(0)) { Debug.Log("Before Shuffle => " + string.Join(", ", list)); Shuffle(list); Debug.Log("After Shuffle => " + string.Join(", ", list)); Debug.Log("*****************************************"); } } }
Getting Random Elements from a List in Unity Game Engine
PrintRandomElements.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PrintRandomElements : MonoBehaviour { List<int> list = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; List<T> GetRandomElements<T>(List<T> inputList, int count) { List<T> outputList = new List<T>(); for (int i = 0; i < count; i++) { int index = Random.Range(0, inputList.Count); outputList.Add(inputList[index]); } return outputList; } void Update() { if(Input.GetMouseButtonDown(0)) { var randomList = GetRandomElements(list, 4); Debug.Log("All elements => " + string.Join(", ", list)); Debug.Log("Random elements => " + string.Join(", ", randomList)); Debug.Log("*****************************"); } } }
Collider Trigger Event Methods(Enter, Exit, Stay) in Unity Game Engine
TriggerEvents.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class TriggerEvents : MonoBehaviour { void OnTriggerEnter(Collider other) { if(other.gameObject.name == "Cylinder") { Debug.Log("Enter"); gameObject.GetComponent<Renderer>().material.SetColor("_Color", Color.red); other.gameObject.GetComponent<Renderer>().material.SetColor("_Color", Color.blue); } } void OnTriggerExit(Collider other) { if(other.gameObject.name == "Cylinder") { Debug.Log("Exit"); gameObject.GetComponent<Renderer>().material.SetColor("_Color", Color.green); other.gameObject.GetComponent<Renderer>().material.SetColor("_Color", Color.white); } } void OnTriggerStay(Collider other) { if(other.gameObject.name == "Cylinder") { Debug.Log("Stay"); transform.localScale += Vector3.one * Time.deltaTime; } } }
Collision Event Methods(Enter, Exit, Stay) in Unity Game Engine
CollisionEvents.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CollisionEvents : MonoBehaviour { void OnCollisionEnter(Collision collision) { if(collision.gameObject.name == "Cube") { Debug.Log("Enter"); gameObject.GetComponent<Renderer>().material.SetColor("_Color", Color.red); } } void OnCollisionExit(Collision collision) { if(collision.gameObject.name == "Cube") { Debug.Log("Exit"); gameObject.GetComponent<Renderer>().material.SetColor("_Color", Color.green); } } void OnCollisionStay(Collision collision) { if(collision.gameObject.name == "Cube") { Debug.Log("Stay"); collision.transform.localEulerAngles += new Vector3(0, 0, -10) * Time.deltaTime; } } }
Event Functions Invoke Order in Unity Game Engine
InvokeOrder.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Reflection; public class InvokeOrder : MonoBehaviour { void Start() { Debug.Log("Start()"); } void Awake() { Debug.Log("Awake()"); } void OnEnable() { Debug.Log("OnEnable()"); } void OnDisable() { Debug.Log("OnDisable()"); } void OnGUI() { Debug.Log("OnGUI()"); } void Update() { Debug.Log("Update()"); } void FixedUpdate() { Debug.Log("FixedUpdate()"); } void LateUpdate() { Debug.Log("LateUpdate()"); } void OnApplicationQuit() { Debug.Log("OnApplicationQuit()"); } void OnDestroy() { Debug.Log("OnDestroy()"); } }
Spin Object in Unity Game Engine
Spin.cs
using UnityEngine; public class Spin : MonoBehaviour { public Vector3 speed = new Vector3(0, 0, 90); void Update() { transform.Rotate(speed * Time.deltaTime, Space.World); } }
Get/Post REST API Data using UnityWebRequest
GetMethod.cs
using System.Collections; using UnityEngine; using UnityEngine.UI; using UnityEngine.Networking; public class GetMethod : MonoBehaviour { InputField outputArea; void Start() { outputArea = GameObject.Find("OutputArea").GetComponent<InputField>(); GameObject.Find("GetButton").GetComponent<Button>().onClick.AddListener(GetData); } void GetData() => StartCoroutine(GetData_Coroutine()); IEnumerator GetData_Coroutine() { outputArea.text = "Loading..."; string uri = "https://my-json-server.typicode.com/typicode/demo/posts"; using(UnityWebRequest request = UnityWebRequest.Get(uri)) { yield return request.SendWebRequest(); if (request.isNetworkError || request.isHttpError) outputArea.text = request.error; else outputArea.text = request.downloadHandler.text; } } }
PostMethod.cs
using System.Collections; using UnityEngine; using UnityEngine.UI; using UnityEngine.Networking; public class PostMethod : MonoBehaviour { InputField outputArea; void Start() { outputArea = GameObject.Find("OutputArea").GetComponent<InputField>(); GameObject.Find("PostButton").GetComponent<Button>().onClick.AddListener(PostData); } void PostData() => StartCoroutine(PostData_Coroutine()); IEnumerator PostData_Coroutine() { outputArea.text = "Loading..."; string uri = "https://my-json-server.typicode.com/typicode/demo/posts"; WWWForm form = new WWWForm(); form.AddField("title", "test data"); using(UnityWebRequest request = UnityWebRequest.Post(uri, form)) { yield return request.SendWebRequest(); if (request.isNetworkError || request.isHttpError) outputArea.text = request.error; else outputArea.text = request.downloadHandler.text; } } }
Create Radio Buttons Behavior Using Toggle Component
RadioButtonSystem.cs
using UnityEngine; using UnityEngine.UI; using System.Linq; public class RadioButtonSystem : MonoBehaviour { ToggleGroup toggleGroup; void Start() { toggleGroup = GetComponent<ToggleGroup>(); } public void Submit() { Toggle toggle = toggleGroup.ActiveToggles().FirstOrDefault(); Debug.Log(toggle.name + " _ " + toggle.GetComponentInChildren<Text>().text); } }
Save/Load Data using Json File(Json Serialization/Deserialization)
WeaponData.cs
//Object of this class will hold the data //And then this object will be converted to JSON [System.Serializable] public class WeaponData { public string Id; public string Name; public string Information; }
JsonReadWriteSystem.cs
using System.IO; using UnityEngine; using UnityEngine.UI; public class JsonReadWriteSystem : MonoBehaviour { public InputField idInputField; public InputField nameInputField; public InputField infoInputField; public void SaveToJson() { WeaponData data = new WeaponData(); data.Id = idInputField.text; data.Name = nameInputField.text; data.Information = infoInputField.text; string json = JsonUtility.ToJson(data, true); File.WriteAllText(Application.dataPath + "/WeaponDataFile.json", json); } public void LoadFromJson() { string json = File.ReadAllText(Application.dataPath + "/WeaponDataFile.json"); WeaponData data = JsonUtility.FromJson<WeaponData>(json); idInputField.text = data.Id; nameInputField.text = data.Name; infoInputField.text = data.Information; } }
Copy and Paste Text Using Clipboard
CopyPasteSystem.cs
using UnityEngine; using UnityEngine.UI; public class CopyPasteSystem : MonoBehaviour { public InputField inputField; public void CopyToClipboard() { TextEditor textEditor = new TextEditor(); textEditor.text = inputField.text; textEditor.SelectAll(); textEditor.Copy(); //Copy string from textEditor.text to Clipboard } public void PasteFromClipboard() { TextEditor textEditor = new TextEditor(); textEditor.multiline = true; textEditor.Paste(); //Copy string from Clipboard to textEditor.text inputField.text = textEditor.text; } }
Save & Load Data Securely Using BinaryFormatter
PlayerData.cs
//Container to hold data [System.Serializable] public class PlayerData { public string playerName; public float playerAge; public int playerClass; }
SaveLoadSystem.cs
using System.IO; using System.Runtime.Serialization.Formatters.Binary; using UnityEngine; using UnityEngine.UI; public class SaveLoadSystem : MonoBehaviour { public InputField nameInputField; public Slider ageSlider; public Dropdown classDropdown; //Path where data file will be stored string filePath; void Awake() { filePath = Path.Combine(Application.dataPath, "playerData.dat"); } public void SavePlayerData() { PlayerData playerData = new PlayerData(); playerData.playerName = nameInputField.text; playerData.playerAge = ageSlider.value; playerData.playerClass = classDropdown.value; Stream stream = new FileStream(filePath, FileMode.Create); BinaryFormatter binaryFormatter = new BinaryFormatter(); binaryFormatter.Serialize(stream, playerData); stream.Close(); } public void LoadPlayerData() { if(File.Exists(filePath)) { Stream stream = new FileStream(filePath, FileMode.Open); BinaryFormatter binaryFormatter = new BinaryFormatter(); PlayerData data = (PlayerData)binaryFormatter.Deserialize(stream); stream.Close(); nameInputField.text = data.playerName; ageSlider.value = data.playerAge; classDropdown.value = data.playerClass; } } }
Subscribe to:
Posts (Atom)