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;
        }
    }
}

Pointer Click on 2D/3D Objects without Script | Event System | Event Trigger | Unity Game Engine

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);
        }
    }
}

Prefab Creation in Unity Game Engine

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);
    }
}

Spin Object Using Animator in Unity Game Engine

Using 'UI Mask' component in Unity Game Engine