Feed REST API Data to Unity UI Components | UnityWebRequest | 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
52
53
54
55
56
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;
    }
}