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