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

Unity向Firebase onCall函数传JSON出现undefined问题及解决方案

为什么Firebase日志提示传入的数据为undefined

Unity侧实现代码

  1. 自定义Question类
public class Question
{
    private string question;
    private string answerA;
    private string answerB;
    private string answerC;
    private string answerD;
    private string rightAnswer;

    public Question(string question, string answerA, string answerB, string answerC, string answerD, string rightAnswer)
    {
        this.question = question;
        this.answerA = answerA;
        this.answerB = answerB;
        this.answerC = answerC;
        this.answerD = answerD;
        this.rightAnswer = rightAnswer;
    }
}
  1. 按钮点击事件逻辑
submitButton.onClick.AddListener(() =>
{
    Question myQuestion = new Question(questionField.text, answerAField.text, 
        answerBField.text, answerCField.text, answerDField.text, rightAnswer.text);
    string json = JsonUtility.ToJson(myQuestion);
    firebaseManager.createQuestion(json);
});
  1. 调用Firebase云函数的方法
public void createQuestion(string json)
{
    var function = FirebaseFunctions.DefaultInstance.GetHttpsCallable("createQuestion");
    function.CallAsync(json).ContinueWithOnMainThread(task =>
    {
        if (task.IsCompleted)
            Debug.Log("done");
    });
}

初始服务端云函数代码

exports.createQuestion = functions.https.onCall((data, context) => {
    console.log(data.answerA);
    console.log(data.answerB);
    return 0;
});

问题现象

运行后Firebase日志提示访问的字段为undefined,换成Dictionary<string,object>类型直接传参不转JSON时,功能就正常。

根因说明

Firebase可调用云函数的CallAsync方法会自动对传入的参数做序列化处理:

  • 传入Dictionary对象时,SDK会自动把它序列化为JSON结构,服务端接收到的data本身就是可直接访问属性的JS对象,所以可以直接读data.answerA
  • 传入已经序列化好的JSON字符串时,SDK会把整个字符串当做参数值序列化,服务端收到的data就是一个纯字符串,自然不能直接访问字符串上不存在的answerA属性,就会返回undefined

解决方案

有两种可选方案,任选其一即可:

方案1:修改服务端代码,对收到的字符串做JSON解析

exports.createQuestion = functions.https.onCall((data, context) => {
    var myObject = JSON.parse(data);
    console.log(myObject.answerA);
    console.log(myObject.answerB);
    return 0;
});

方案2:Unity侧直接传可序列化对象,不提前转JSON

先把Question类的字段改为public(否则JsonUtility默认不会序列化private字段),之后调用CallAsync时直接传myQuestion实例即可,不需要自己调用JsonUtility.ToJson,Firebase SDK会自动完成序列化,服务端可以直接访问data的属性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 19:39:03