我正在尝试运行 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,
};
});
云函数的参数实际上是整个
request
对象,您在 C# 代码中传递的数据位于其中的 data
属性中。
所以:
exports.getNumbers = functions.https.onCall((request) => {
// Numbers passed from the client.
const firstNumber = request.data.firstNumber;
const secondNumber = request.data.secondNumber;
...
另请参阅有关 可调用函数 的 Firebase 文档,其中有示例说明了这一点。