c# - Unity UnityWebRequest 没有返回值

标签 c# unity3d httpwebrequest coroutine ienumerator

我有一些代码可以从数据库中获取一些数据。在我的游戏中使用。 我已经设置了一个协同程序来统一使用 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() 来记录数据,而不是 IEnumerator() 中的 debug.log

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

最佳答案

GetText 函数内完成 UnityWebRequest 请求后,您必须调用结果 Action:

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

新的 GetText 函数:

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

关于c# - Unity UnityWebRequest 没有返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51307424/

相关文章:

c# - 为通用应用程序读取/写入异步文件

c# - 如何检查字符串是否包含字符串数组中的字符串?

c# - 移动设备上的 Unity3d Application.OpenURL(Android 和 iOS)

c# - Unity 开发人员如何限制从 Object 派生的泛型类型参数?

c# - 如何使用 C# 将 JSON 发布到服务器?

c# - 如何在不使用查询语法的情况下在 Entity Framework 中进行左外连接?

javascript - 如何使用两个确认对话框?

c# - 如何在我需要时打开门

.net - 当请求不是来自浏览器时,HttpContext 为 null

c# - 如何使用 C# 连接到路由器 "panel"