You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity C#使用RestClient请求API无法正常退出函数返回值为null

问题根因
  • 你使用的Proyecto26.RestClient的Request方法是异步回调模式,外层basicRequest函数不会等待网络请求完成就会执行完毕,此时Then回调还没触发,outputs自然为null。
  • 你写在Then回调内的return outputs是回调函数的返回值,不属于外层basicRequest的返回值,而basicRequest声明了返回string却没有在外层逻辑写返回语句,因此会报没有合法返回值的编译错误。
解决思路

方案1:回调委托(最常用,无版本依赖)

将方法改为无返回值,通过回调参数传递请求结果,适合所有Unity版本:

// 修改方法签名,增加回调参数
public void basicRequest(int requestTyp, Action<string> onRequestFinish)
{
    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);

    RestClient.Request(new RequestHelper
    {
        Uri = basicRequestPage,
        Method = "POST",
        Timeout = 10,
        ParseResponseBody = false,
        BodyRaw = outputToServer
    }).Then(response =>
    {
        // 请求成功,把结果传给回调
        onRequestFinish?.Invoke(response.Text);
    }).Catch(err =>
    {
        var error = err as RequestException;
        // 失败可以传null或者错误信息,按需调整
        onRequestFinish?.Invoke(null);
        EditorUtility.DisplayDialog("Error Response", error.Response + "", "Ok");
    });
}

// 调用示例
// basicRequest(0, (result) => {
//    if(result != null) Debug.Log("请求结果:" + result);
// });

方案2:async/await(代码更简洁)

Proyecto26.RestClient返回的Promise支持异步等待,可将方法改为异步返回:

using System.Threading.Tasks;

public async Task<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);

    try
    {
        var response = await RestClient.Request(new RequestHelper
        {
            Uri = basicRequestPage,
            Method = "POST",
            Timeout = 10,
            ParseResponseBody = false,
            BodyRaw = outputToServer
        });
        return response.Text;
    }
    catch (RequestException err)
    {
        EditorUtility.DisplayDialog("Error Response", err.Response + "", "Ok");
        return null;
    }
}

// 调用示例:
// string result = await basicRequest(0);
// 注意不要用.Result同步阻塞,会卡死Unity主线程
注意事项
  • 你当前代码中使用的EditorUtility.DisplayDialog仅能在Unity编辑器环境生效,打包发布后会失效,实际生产环境需要替换为UGUI实现的自定义弹窗。
  • 不要尝试用同步阻塞的方式等待网络请求返回,会导致主线程卡顿,用户体验极差。

内容的提问来源于stack exchange,提问作者daniel robbins

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.08 01:18:03