How can i use a parameter given from a json file?

Viewed 57

i need to use this json file:

{
"player": [
    {
        "X":7.214575709504705,
        "Z":28.484783109249697,
        "ID":"116",
        "Speed":1.0
    }
  ]
}

From this file i need the "Speed" to set this as a parameter inside the unity inspector and move my agent or character with this speed from the json file, at this moment i have this JsonReader.

using System.Collections.Generic;
using UnityEngine;

public class Reader : MonoBehaviour
{
public TextAsset jsonData;
public PlayerList players = new PlayerList();

[System.Serializable]
public class Player
{
    public float X;
    public float Z;
    public string ID;
    public float Speed;
}
[System.Serializable]
public class PlayerList
{
    public Player[] player;
}
// Start is called before the first frame update
void Start()
{
    players = JsonUtility.FromJson<PlayerList>(jsonData.text);
}
}

Grateful for any help with this.

1 Answers

I really really really recommend you use Newtonsoft instead.

https://github.com/jilleJr/Newtonsoft.Json-for-Unity

You will be able to serialize to list or array directly too, so you will only need as a member variable public Player[] players; instead of public PlayerList players;

With Newtonsoft it will look like this (you need to add a new library):

using Newtonsoft.Json;

players = JsonConvert.Deserialize<Player[]>(jsonData.text);

Related