0

I have a problem with unity and JSON. Well I need to save a name and score from a game, I think Json it's a great option but I've never used them.

I understand the basics, how to read one JsonObject but the problem I don't know how to create a new object.

Later i try to create an array of object in Json and I don't know how to read them.

this is my idea.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;


public class Score : MonoBehaviour {
    string path;
    string jsonString;
    // Use this for initialization
    void Start () {
        path = Application.dataPath + "/ScoreRecords.json";
        jsonString = File.ReadAllText (path); 
        ListaRecords listaRecords = JsonUtility.FromJson<ListaRecords> (jsonString);
        print(listaRecords);
        foreach(Record record in listaRecords){
            Debug.Log ("nombre: " + record.name + "score: " + record.score);
        }

    }

    // Update is called once per frame
    void Update () {

    }
}


[System.Serializable]
public class Record{
    public string name;
    public int score;
}

[System.Serializable]

public class ListaRecords{
    public List<Record> Records;
}

and this is my Json file

{
    "Records": [
        {"nombre":"daniel", "puntos":100},
        {"nombre":"Adrian", "puntos":200}
    ]
}

Thanks, I need this.

Zoran Pandovski
  • 2,312
  • 14
  • 24
Dani Vil
  • 1
  • 2
  • You write and read from `Application.persistentDataPath`. See duplicate for a simplified wrapper to read and save game data – Programmer Feb 27 '18 at 00:42
  • Have a look at [JsonUtility](https://docs.unity3d.com/ScriptReference/JsonUtility.html) I think is does exactly what you need. – derHugo Feb 27 '18 at 21:23

0 Answers0