无法正常退出功能



我有一个c# unity函数,我正试图从web服务器请求一些json,但由于某种原因,它没有退出我想要它的函数:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Proyecto26;
using UnityEditor;
using UnityEngine.Networking;
using System.Text;
using TMPro;
using SimpleJSON;
public class APIRequest
{
// string basicRequestPage = "****";
string basicAPI_Key = "****";
// Start is called before the first frame update
string outputs;

public string basicRequest(int requestTyp)
{

auth test1 = new auth();
test1.key = basicAPI_Key;

switch (requestTyp)
{
case 0:
test1.request = "deckList";
break;
case 1:
test1.request = "card";
break;
}
string output = JsonConvert.SerializeObject(test1);
byte[] outputToServer = Encoding.ASCII.GetBytes(output); ;

//Debug.Log(output);
RestClient.Request(new RequestHelper
{
Uri = basicRequestPage,
Method = "POST",
Timeout = 10,
//EnableDebug = true,
ParseResponseBody = false, //Don't encode and parse downloaded data as JSONe
BodyRaw = outputToServer
}).Then(response =>
{
// EditorUtility.DisplayDialog("Status", response.Text, "Ok");
var rest = response.Text;
//Debug.Log(rest);
outputs = rest.ToString();
//EditorUtility.DisplayDialog("Status", outputs, "Ok");
return outputs;
}).Catch(err =>
{
var error = err as RequestException;
EditorUtility.DisplayDialog("Error Response", error.Response + "", "Ok");

}

);

}
}

链接到代码,因为它不能与内置的代码文本

一起工作它作为一个方法工作得很好,但一直抱怨我没有从函数返回一个有效的值。当我尝试返回从API获得的值时,即输出变量,它说它为空。我试过把它放在函数中,放在一个公共变量中。但现在有用了。

任何想法?

当你使用承诺时,你也需要从该方法返回一个承诺(承诺链):

public IPromise<string> basicRequest(int requestTyp)
{
return RestClient.Request(new RequestHelper
{
Uri = basicRequestPage,
Method = "POST",
Timeout = 10,
//EnableDebug = true,
ParseResponseBody = false, //Don't encode and parse downloaded data as JSONe
BodyRaw = outputToServer
}).Then(response => response.Text.ToString());
}

更多细节,请查看Unity的RestClient使用的Promises库。

您已经定义了类型为string的输出,但是您没有在所有出口返回字符串。在catch之后,您必须在方法的末尾或catch中返回一个字符串。我添加的最后一行return "";应该可以解决这个问题。

public string basicRequest(int requestTyp)
{
auth test1 = new auth();
test1.key = basicAPI_Key;
switch (requestTyp)
{
case 0:
test1.request = "deckList";
break;
case 1:
test1.request = "card";
break;
}
string output = JsonConvert.SerializeObject(test1);
byte[] outputToServer = Encoding.ASCII.GetBytes(output);
//Debug.Log(output);
RestClient.Request(new RequestHelper
{
Uri = basicRequestPage,
Method = "POST",
Timeout = 10,
//EnableDebug = true,
ParseResponseBody = false, //Don't encode and parse downloaded data as JSONe
BodyRaw = outputToServer
}).Then(response =>
{
// EditorUtility.DisplayDialog("Status", response.Text, "Ok");
var rest = response.Text;
//Debug.Log(rest);
outputs = rest.ToString();
//EditorUtility.DisplayDialog("Status", outputs, "Ok");
return outputs;
}).Catch(err =>
{
var error = err as RequestException;
EditorUtility.DisplayDialog("Error Response", error.Response + "", "Ok");
}
);
return ""; //<----- this here
}

最新更新