LoginSignup
3
2

More than 5 years have passed since last update.

UnityのWWWでjsonをポーリング

Last updated at Posted at 2017-12-13

1秒ごとにjsonを読みに行くコード。
コルーチンが何なのかよくわかってませんが、とりあえず動いた。


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

public class Polling : MonoBehaviour {

    private string path = "https://hoge.com/json/hoge.json";

    void Start () {  
        Request();      
    }

    void Request()
    {
        // コルーチンを実行  
        StartCoroutine ( RequestJson(OnRequest) );      
    }

    void OnRequest()
    {
        Debug.Log("complete");
        Invoke("Request",1f);
    }

    IEnumerator RequestJson (Action callback) {

        using(WWW www = new WWW(path)){

            yield return www;

            if(!string.IsNullOrEmpty(www.error)){
                Debug.LogError("www Error:" + www.error);
                yield break;
            }

            Debug.Log( www.text );
            JSONObject json = new JSONObject(www.text);

            callback();

        }

    }

}

※追記 WWW → UnityWebRequest に改造

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

public class ApiPolling : MonoBehaviour {

    protected string _url = "https://hoge.com/json/hoge.json";
    protected string _json = "";
    protected JSONObject _jsonObject;


    void Start () {  
        Request();      
    }

    void Request()
    {

        // コルーチンを実行  
        StartCoroutine ( RequestJson(OnRequest,OnError) );      
    }

    void OnRequest()
    {
        Debug.Log("OnRequest");
        Invoke("Request",1f);
    }

    void OnError(){
        //error
        Debug.LogWarning("ApiPolling err");
        Invoke("Request",1f);
    }

    IEnumerator RequestJson (Action callback,Action callbackError) {

                UnityWebRequest www = UnityWebRequest.Get(_url);
                www.timeout = 1;

                yield return www.Send();

                if(www.isNetworkError) {
                    Debug.LogWarning(_url);
                    //Debug.LogError("www Error:" + www.error);
                    callbackError();
                    yield break;
                }
                else {
                    _json = www.downloadHandler.text;
                    _jsonObject = new JSONObject(_json);
                    callback();
                }
    }

}

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2