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);
}
添加回答
舉報