Feed REST API Data to Unity UI Components | HttpClient | Unity Game Engine


WeaponsData.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
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;
    }
}