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