툴/유니티

[C#]유니티 JSON 데이터 받아오기

스튜디오 오버그래픽스 2021. 8. 2. 02:57

유니티에서 Json 데이터 받기

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[System.Serializable]
public class JsonData
{
	public int A;
    public string B;
}

public class JsonReceiver : MonoBehaviour
{

    public static JsonData data1;
    WWW www;
    string T;
    public string url = "Json데이터 받아올 URL주소";

    void Start()
    {
        InvokeRepeating("CoroutineLoad", 0, 1f); //Json데이터 반복해서 업데이트 
    }

    void Update()
    {
            Debug.Log(data1.B);
    }

 
    void CoroutineLoad()
    {
        StartCoroutine("JsonLoad");
    }

    IEnumerator JsonLoad()  //Json데이터 로드하는 코루틴 함수
    {
        www = new WWW(url);
        yield return www;
        T = www.text;
        data1 = JsonUtility.FromJson<JsonData>(T);
        Debug.Log("Json Updated");
    }

}

URL주소로 Json데이터를 가져오고

Json데이터가 int형인 A와 String형인 B가 있는 경우

0.1초마다 새로 갱신해서 B의 값을 콘솔창에 보여주는 코드