I am trying to send data from JS to C# in Unity in a WebGL project, but I am not as familiar with javascript and JSON.
In the JS code, I am serializing an array of objects from js with Json.Stringify, and that is sent to Unity as a string. This is what comes through to Unity...
[
[],[],[],[],
[
{
"damage": 0,
"opaque": false,
"safe": false
}
],
[
{
"damage": 0,
"opaque": false,
"safe": false
}
]
]
I did not write the js code, so I am not sure what exactly to post. If it seems like my Unity code is okay, I will try to see what I can share from js.
I am not sure why there are empty brackets above. I wonder if unity is getting stuck trying to serialize those empty sets.
I made two Serializable classes in Unity for the incoming objects.
[System.Serializable]
public class minimap
{
public int damage;
public bool opaque;
public bool safe;
}
[System.Serializable]
public class minimaps
{
public minimap[] minimapArray;
}
On a gameObject, I placed a script that is called from JS. The "Json convert completed" works, but the minimap loop does not. The array seems to have something in it, but not what I was hoping for unless I am not accessing it properly.
public class GameController : MonoBehaviour
{
public JsonDeserialize(string minimap)
{
minimaps minimaps = JsonUtility.FromJson<minimaps>(minimap);
if(minimaps != null) _debugText.text = "JSON convert completed";
foreach (minimap mm in minimaps.minimapArray)
{
_debugText.text = "Damage: " mm.damage "opaque: " mm.opaque;
}
}
}
Thanks for reading and any help!
CodePudding user response:
try this
if(!string.IsNullOrEmpty(minimap)
{
minimap[][] minimaps = JsonUtility.FromJson<minimaps[][]>(minimap);
if(minimaps!=null)
{
foreach (var mms in minimaps)
{
if(mms==null) _debugText.text ="Error: mms is null";
else
foreach (minimap mm in mms)
_debugText.text = "Damage: " mm.damage "opaque: " mm.opaque;
}
}
} else _debugText.text ="Error: minimaps is null";
} else _debugText.text ="Error: minimap is an empty string";
but I highly recommend you to google and istall Newtonsoft.Json for Unity3d
using Newtonsoft.Json;
minimap[][] minimaps = JsonConvert.DeserializeObject<minimaps[][]>(minimap);