#c# #json #unity3d
#c# #json #unity3d
Вопрос:
Я пытаюсь прочитать переменные массива json, который считывается в скрипте Unity. Это то, что у меня есть:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System;
public class json_example02 : MonoBehaviour
{
public string[] newObject;
void Start()
{
Debug.Log("jsonScript start");
// create object
jasonClass newObject = new jasonClass();
// read from json file: succesful
string jsonread = File.ReadAllText(Application.dataPath "/valuesexample.json");
newObject = JsonUtility.FromJson<jasonClass>(jsonread);
Debug.Log(newObject.Values.Length);// reads correctly
// trying to acces variables here, but it returns empty
Debug.Log("Values: " newObject.Values[0]);
Debug.Log("Values: " newObject.Values[1]);
Debug.Log("Values: " newObject.Values[2]);
// write to file: succesful
string jsonwrite = JsonUtility.ToJson(newObject);
File.WriteAllText(Application.dataPath "/saveFileReturn.json", jsonwrite);
}
[Serializable]
public class jasonClass
{
public Valuesarray[] Values;
}
[Serializable]
public class Valuesarray
{
public string Text;
//public string Text2;
}
}
Это формат файла чтения json:
{"Values":[{
"Text":"A"
},
{
"Text":"B"
},
{
"Text":"C"
},
{
"Text":"D"
},
{
"Text":"E"
}]
}
Проверка чтения и записи в другой файл. Вывод:
{"Values":[{"Text":"A"},{"Text":"B"},{"Text":"C"},{"Text":"D"},{"Text":"E"}]}
Пока все хорошо, но я не понимаю, как читать отдельные переменные по indexnumber, например:
Debug.Log("Values: " newObject.Values[0]);
Который возвращает пустой.
Как я могу получить доступ к этим переменным по номеру индекса?
Заранее спасибо.
Ответ №1:
Вы почти на месте!
Поскольку ваш класс Valuesarray имеет текстовую переменную, ваш код должен вызывать ее:
Debug.Log("Values: " newObject.Values[0].Text);
Debug.Log("Values: " newObject.Values[1].Text);
Debug.Log("Values: " newObject.Values[2].Text);
Комментарии:
1. Большое спасибо, это сработало! Я не ожидал такого решения, но оно определенно помогает мне развивать сценарий дальше.
2. @Hieronymus Удачи с вашим проектом. Приветствия!