2015-03-23 11 views
0

Я пытаюсь получить json из веб-службы, но я получаю эту ошибку, когда пытаюсь использовать result.text, она вызывает ошибку «WWW еще не готов к загрузке», если я не знаю, т попытаться использовать эту переменную, я не получаю какую-либо ошибкуWWW еще не загружен

using UnityEngine; 
using System.Collections; 
using System.Collections.Generic; 
using Boomlagoon.JSON; 

public class ClassInfoScript : MonoBehaviour { 

private IEnumerator coroutine; 
public string name; 
private bool showInfo = false; 
//esta variable es para controlar que solo seconecte uan vez al entrar en un collider 
private bool connected = false; 
private bool isClass = false; 
private bool isDependency = false; 
private bool isOffice= false; 
public GUIStyle myStyle; 
public GUIStyle labelStyle; 
enum Types{classroom, dependency, office}; 


void Start(){ 

} 
void OnGUI() { 
    if (showInfo) { 
     GUI.Box (new Rect (Screen.width * 0.02f, Screen.height * 0.02f, Screen.width * 0.15f, Screen.height * 0.75f), "", myStyle); 
     WWW result = null; 
     if (isClass) { 
      if(!connected){ 
       result = get ("http://localhost/ws/get/clase/D1"); 

      } 
      //I get the error here when I try to use result.text 
      JSONObject jo = JSONObject.Parse(result.text); 
     connected = true; 
    } 
} 
//obtener el nombre 
public void setName(string value){ 
    name = value; 
} 
//cambiar el nombre 
public string getName(){ 
    return name; 
} 
//cambiar el valor de showInfo 
public void changeInfoState(){ 
    showInfo = !showInfo; 
} 
public void changeClass(){ 
    isClass = !isClass; 
} 
public void changeDependency(){ 
    isDependency = !isDependency; 
} 
public void changeOffice(){ 
    showInfo = !showInfo; 
} 
public WWW get(string url){ 
    WWW w = new WWW (url); 
    StartCoroutine(AskWebservice(w)); 
    return w; 
} 

IEnumerator AskWebservice(WWW w){ 
    Debug.Log ("Coroutine started"); 
    yield return w; 
    if (w.error == null){ 
     Debug.Log("WWW Ok!: " + w.text); 
    } else { 
     Debug.Log("WWW Error: "+ w.error); 
    }  

} 

} 

Теперь моя OnGUI функция, как это

void OnGUI() { 
    if (showInfo) { 
     GUI.Box (new Rect (Screen.width * 0.02f, Screen.height * 0.02f, Screen.width * 0.15f, Screen.height * 0.75f), "", myStyle); 
     WWW result = null; 
     JSONObject jo = null; 

     if (isClass) { 
      if(!connected){ 
       string url = "http://localhost/ws/get/clase/"+getName(); 
       StartCoroutine(HandleWWWRequest(url, (www) => { 
        jo = JSONObject.Parse(www.text); 
        Debug.Log(jo.GetString("info")); 
        connected = true; 
       })); 
      } 
      GUI.Label (new Rect (Screen.width * 0.03f, Screen.height * 0.04f, Screen.width * 0.15f, Screen.height * 0.75f), jo.GetString("nombre"), labelStyle); 
      GUI.Label (new Rect (Screen.width * 0.03f, Screen.height * 0.15f, Screen.width * 0.15f, Screen.height * 0.75f), jo.GetString("info"), labelStyle); 

     } else if (isDependency) { 
      /*coroutine = AskWebservice ("dependencia", name, Types.dependency); 
      if(!connected) 
       StartCoroutine (coroutine); 

      GUI.Label (new Rect (Screen.width * 0.03f, Screen.height * 0.04f, Screen.width * 0.15f, Screen.height * 0.75f), response [0], labelStyle); 
      GUI.Label (new Rect (Screen.width * 0.03f, Screen.height * 0.15f, Screen.width * 0.15f, Screen.height * 0.75f), response [1], labelStyle); 
      GUI.Label (new Rect (Screen.width * 0.03f, Screen.height * 0.20f, Screen.width * 0.15f, Screen.height * 0.75f), response [2], labelStyle);*/ 
     } 
     connected = true; 
    } 
} 

Но в этом две линии

GUI.Label (new Rect (Screen.width * 0.03f, Screen.height * 0.04f, Screen.width * 0.15f, Screen.height * 0.75f), jo.GetString("nombre"), labelStyle); 
GUI.Label (new Rect (Screen.width * 0.03f, Screen.height * 0.15f, Screen.width * 0.15f, Screen.height * 0.75f), jo.GetString("info"), labelStyle); 

Я не могу использовать поля jsonobject в ярлыках, это нули, и я попытался сохранить эти поля в других переменных и в списке, но он не работает, как я могу хранить поля jsonobject, чтобы использовать их после i выполните coroutine? Я не использовал эти фледы в ярлыках.

+0

Я отредактировал ваш заголовок. Пожалуйста, смотрите: «Если вопросы включают« теги »в их названиях?] (Http://meta.stackexchange.com/questions/19190/), где консенсус« нет, они не должны ». –

+0

Повторите свое обновление на вопрос: переместите любой код, который должен использовать возвращенные данные WWW _inside_ блок кода. В вашем случае перемещение GUI.Label вызывает только под "connected = true;" линия. – Huacanacha

+0

Это первое, что я пробовал, но значения не указаны на этикетке, метки пусты. – AFS

ответ

0

Ваша функция get является неблокирующим вызовом. StartCoroutine необходимо использовать с доходностью, например yield return StartCoroutine(...), чтобы ваш код дождался завершения сопрограммы. Поскольку WWW еще не закончен, результата пока нет.

попробовать что-то вроде этого:

IEnumerator HandleWWWRequest(string url, System.Action<WWW> onSuccess) { 
    WWW www = new WWW(url); 
    yield return www; 
    if (string.IsNullOrEmpty(www.error)) { 
     onSuccess(www); 
    } else { 
     Debug.LogWarning("WWW request returned an error."); 
    } 
} 

... 

if (isClass) { 
    if(!connected){ 
     string url = "http://localhost/ws/get/clase/D1"; 
     // Non-blocking... success handling code is passed as a lambda 
     StartCoroutine(HandleWWWRequest(url, (www) => { 
      JSONObject jo = JSONObject.Parse(www.text); 
      connected = true; 
     })); 
    } 
} 

Чтобы сохранить код ясно, что я не включал OnError обратного вызова, но вы можете легко добавить его.