代码之家  ›  专栏  ›  技术社区  ›  FutureCake

Unity UnityWebrequest未返回值

  •  2
  • FutureCake  · 技术社区  · 7 年前

    我有一些代码从数据库中获取一些数据。在我的游戏中使用。 我已经设置了一个协同程序,用Unity中的WWW框架获取这些数据。 但是当我运行我的代码时,数据永远不会记录在我的yield return函数中。为什么会这样?有关不起作用的点,请参见下面的代码:

    using System;
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.Networking;
    
    public class Main : MonoBehaviour {
    
        void Start () {
            Debug.Log("run ma routine");
            StartCoroutine(GetText("http://localhost/artez/praktijk_opdracht/interface_v4/app/php/get_fashion.php", (result) =>{
                Debug.Log(result); // this log function is never logging a value.. Why is this?
            }));
        }
    
        void Update () 
        {
        }
    
        IEnumerator GetText(string url, Action<string> result) {
            UnityWebRequest www = UnityWebRequest.Get(url);
            yield return www.SendWebRequest();
    
            if(www.isNetworkError || www.isHttpError) {
                Debug.Log(www.error);
            }
            else {
                Debug.Log(www.downloadHandler.data); // this log is returning the requested data. 
            }
        }
    }
    

    我想要的是 StartCoroutine() 记录数据而不是 debug.log IEnumerator()

    如果有什么需要更多的解释,我很乐意提供。

    1 回复  |  直到 7 年前
        1
  •  2
  •   Programmer    7 年前

    你必须调用结果 Action 之后 UnityWebRequest 请求在 GetText 功能:

    if (result != null)
        result(www.downloadHandler.text);
    

    新的 获取文本 功能:

    IEnumerator GetText(string url, Action<string> result)
    {
        UnityWebRequest www = UnityWebRequest.Get(url);
        yield return www.SendWebRequest();
    
        if (www.isNetworkError || www.isHttpError)
        {
            Debug.Log(www.error);
            if (result != null)
                result(www.error);
        }
        else
        {
            Debug.Log(www.downloadHandler.data); // this log is returning the requested data. 
            if (result != null)
                result(www.downloadHandler.text);
        }
    }