如何从服务器下载文本?

时间:2019-01-25 19:10:40

标签: c# unity3d server

我需要从服务器上下载JSON并在我的代码中反序列化才能使用它。

我知道,我需要UnityWebRequest和一个协程。我了解两种方式。 我可以启动Coroutine,将请求发送到服务器并处理该被调用者协程中接收到的数据,或者 我可以StartCoroutine,发送请求并将结果保存到类私有变量。那时,在StartCoroutine之后,我可以执行while(variable == null),然后在调用方方法中处理数据

private void Start()
    {
        StartCoroutine(LoadPagesId("SomeURL.com"));
    }

    private IEnumerator LoadPagesId(string url)
    {
        var request = UnityWebRequest.Get(url);
        yield return request.SendWebRequest();

        var data = request.downloadHandler.text;
        request.Dispose();

        // Do something with data
    }

OR

private string _str;

    private void Start()
    {
        StartCoroutine(LoadPagesId("SomeURL.com"));
        while (_str == null)
        {

        }
        // Do something with data
    }

    private IEnumerator LoadPagesId(string url)
    {
        var request = UnityWebRequest.Get(url);
        yield return request.SendWebRequest();

        _str = request.downloadHandler.text;
        request.Dispose();
    }

还有其他方法,没有全局变量和扩展的LOAD方法吗?

1 个答案:

答案 0 :(得分:1)

是的,例如只需添加回调:

private void Start()
{
    StartCoroutine(LoadPagesId("SomeURL.com"), HandleSuccess, HandleError);

    // Or as lambda expressions
    StartCoroutine(LoadPagesId("SomeURL.com"), success => {
       // do something with success
    }, error => {
       // do something with error
    });
}

private IEnumerator LoadPagesId(string url, Action<string> successCallback, Action<string> errorCallback)
{
    var request = UnityWebRequest.Get(url);
    yield return request.SendWebRequest();

    if(www.error)
    {
        errorCallback?.Invoke(www.error);
    } 
    else
    {
        successCallback?.Invoke(request.downloadHandlet.text);
    }
}

private void HandleSuccess(string result)
{
    // Do something
}

private void HandleError(string error)
{
    // Do something
}