2 回答

TA贡献1821条经验 获得超5个赞
您可以发送字符串或数字,所以我要做的是创建一个 js 对象,其中包含您需要的数据,然后调用JSON.stringify它以将其转换为字符串,然后使用以下方式发送unityInstance.SendMessage:
function sendToUnity(obj) {
unityInstance.SendMessage('MyGameObject', 'MyMethod', JSON.stringify(obj));
}
// in a script attached to a gameobject named "MyGameObject"
void MyMethod(string s)
{
Debug.Log(s);
// decode from json, do stuff with result etc
}
至于当数据为 JSON 字符串形式时您可以对其执行哪些操作,一旦您在 Unity 中拥有它,您可以使用各种解决方案来解码 JSON 字符串。有关详细信息,请参阅在 Unity 中序列化和反序列化 Json 和 Json 数组。
所以如果你的 js 看起来像这样:
function sendToUnity(obj) {
unityInstance.SendMessage('MyGameObject', 'MyMethod', JSON.stringify(obj));
}
sendToUnity({
playerId: "8484239823",
playerLoc: "Powai",
playerNick:"Random Nick"
});
你可以在 Unity 中做这样的事情:
[Serializable]
public class Player
{
public string playerId;
public string playerLoc;
public string playerNick;
}
...
void MyMethod(string s)
{
Player player = JsonUtility.FromJson<Player>(s);
Debug.Log(player.playerLoc);
}
添加回答
举报