在unity webgl中发送带有数组参数的消息

SendMessage with array paramter in unity webgl

Unity SendMessage只能传一个参数,可以是数组。所以我正在为 javascript 调用我的 sendMessage 并调用 C# 方法(实际上是 webgl 方法)

var arr = [x,y,z];
gameInstance.SendMessage("Cube","SetGameObjectPosition",arr);

但出现此错误

Invoking error handler due to

Uncaught 2,2,2 is does not have a type which is supported by SendMessage. [Violation] 'click' handler took 8994ms blob:http://localhost/1ff50200-cb3a-4367-ab45-f02e9734fac2:2 Uncaught 2,2,2 is does not have a type which is supported by SendMessage.

SendMessage @ blob:http://localhost/1ff50200-cb3a-4367-ab45-f02e9734fac2:2

SendMessage @ UnityLoader.js:4

SetObjectPosition @ (index):44

onclick @ (index):65 (index):65

[Violation] 'click' handler took 9000ms

来自SendMessage Docu

SendMessage(objectName, methodName, value);

Where objectName is the name of an object in your scene; methodName is the name of a method in the script, currently attached to that object; value can be a string, a number, or can be empty.

-> 不,它不能是一个数组


但您似乎想传递一个位置,因此作为一种解决方法,您可以传递像“2,2,2”这样的字符串并使用

string[] numberStrings = ("2,2,2").Split(",");
float x = float.TryParse(numberStrings[0], out x) ? x : 0;
float y = float.TryParse(numberStrings[1], out y) ? y : 0;
float z = float.TryParse(numberStrings[2], out z) ? z : 0;

或类似的东西

您可以传递一个 json 字符串:

var pos = {x:1,y:2,z:3};
gameInstance.SendMessage("Cube","SetGameObjectPosition", JSON.stringify(pos));

统一:

void SetGameObjectPosition(string data)
{
    var position = JsonUtility.FromJson<Vector3>(data);
}