Untiies JsonUtility class creates an object, but does not set it's variables.
I'm sure the code is correct, since it worked earlier today. Also tjeked with guides.
public class Player
{
public int speed;
public int health;
public int x;
public int y;
}
public class Testing : MonoBehaviour
{
[SerializeField] private TextAsset _textAsset;
void Start()
{
Player p = JsonUtility.FromJson<Player>(_textAsset.text);
Debug.Log(p.speed); // should print 5
}
}
{
"player": {
"speed": 5,
"health": 3,
"x": 0,
"y": -4
}
}
The above worked earlier today, and I'm unsure what made it stop. And did input the correct text asset file.
What I think broke it. Went into Visual Studio and compilede once.
I triede to make a new project, but with no success.
The assets are in a Unity package. The following link expires in 7 days. https://easyupload.io/dkmrnd
CodePudding user response:
What you have in your JSON is not the structure your code expects.
First of all yes your player class needs to be
[Serializable]
public class Player
{
// fields here NO properties!
}
However, your JSON is further nested!
It either needs to be only
{
"speed": 5,
"health": 3,
"x": 0,
"y": -4
}
Or you need an according wrapper class
[Serializable]
public class JsonRoot
{
public Player player;
}
and then you would need to do
Player p = JsonUtility.FromJson<JsonRoot>(_textAsset.text).player;