Unity调用Firebase云函数异常:请求数据始终为空
问题:Unity调用Firebase Cloud Functions时传入参数为空
尝试运行Unity版Firebase Cloud Functions官方快速入门示例,但从Unity调用函数时传入的参数数据(对象字典)始终为空。已尝试更换不同版本的Firebase SDK,问题依旧,求排查方案。
Unity端代码
void Start() { StartCoroutine(AddNumbers(7, 7)); } protected IEnumerator AddNumbers(int firstNumber, int secondNumber) { var functions = FirebaseFunctions.GetInstance(FirebaseApp.DefaultInstance); var func = functions.GetHttpsCallableFromURL("https://getnumbers-dxhi3lnaew-uc.a.run.app"); var data = new Dictionary<string, object>(); data["firstNumber"] = firstNumber; data["secondNumber"] = secondNumber; var task = func.CallAsync(data).ContinueWithOnMainThread((callTask) => { if (callTask.IsFaulted) { // The function unexpectedly failed. Debug.Log("FAILED!"); Debug.Log(String.Format(" Error: {0}", callTask.Exception)); return; } // The function succeeded. var result = (IDictionary)callTask.Result.Data; Debug.Log(String.Format("AddNumbers: {0}", result["operationResult"])); }); yield return new WaitUntil(() => task.IsCompleted); }
云函数代码
'use strict'; const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp(); // Adds two numbers to each other. exports.getNumbers = functions.https.onCall((data) => { // Numbers passed from the client. const firstNumber = data.firstNumber; const secondNumber = data.secondNumber; // Checking that attributes are present and are numbers. if (Number.isFinite(firstNumber) || !Number.isFinite(secondNumber)) { // Throwing an HttpsError so that the client gets the error details. throw new functions.https.HttpsError('invalid-argument', '!The function ' + 'must be called with two arguments "firstNumber" and "secondNumber" ' + 'which must both be numbers.'); } // returning result. return { firstNumber: firstNumber, secondNumber: secondNumber, operator: '+', operationResult: firstNumber + secondNumber, }; });
排查方案
- 调用方式不匹配:你当前用
GetHttpsCallableFromURL直接调用HTTP URL,但云函数是onCall类型的Callable函数。这类函数要求客户端用SDK的标准Callable接口调用,直接URL访问会导致参数解析失败。
解决:替换为functions.GetHttpsCallable("getNumbers"),确保函数名和云函数的exports.getNumbers一致。 - 参数校验逻辑错误:云函数里的判断条件写反了,原代码
if (Number.isFinite(firstNumber) || !Number.isFinite(secondNumber))会在第一个参数是数字时就抛出错误,让你误以为参数为空。应改为:if (!Number.isFinite(firstNumber) || !Number.isFinite(secondNumber)) - Firebase初始化不完整:确保Unity端Firebase依赖初始化完成后再调用函数,修改Start方法:
void Start() { FirebaseApp.CheckAndFixDependenciesAsync().ContinueWithOnMainThread(task => { if (task.Result == DependencyStatus.Available) { StartCoroutine(AddNumbers(7, 7)); } else { Debug.LogError("Firebase dependencies failed to initialize"); } }); } - 重新部署云函数:确认代码修改后重新部署,执行命令:
firebase deploy --only functions:getNumbers
内容的提问来源于stack exchange,提问作者Timur Gudkov
相关产品推荐
相关产品推荐

