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