Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从Unity中的json文件访问数组变量_C#_Json_Unity3d - Fatal编程技术网

C# 从Unity中的json文件访问数组变量

C# 从Unity中的json文件访问数组变量,c#,json,unity3d,C#,Json,Unity3d,我试图读取在Unity脚本中读取的json数组的变量。 这就是我所拥有的: using System.Collections; using System.Collections.Generic; using UnityEngine; using System.IO; using System; public class json_example02 : MonoBehaviour { public string[] newObject; void Start()

我试图读取在Unity脚本中读取的json数组的变量。 这就是我所拥有的:

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;
    }
}
正在检查对另一个文件的读写。输出:

{"Values":[{"Text":"A"},{"Text":"B"},{"Text":"C"},{"Text":"D"},{"Text":"E"}]}
到目前为止一切都很好,但我不知道如何通过indexnumber读取单个变量,例如:

Debug.Log("Values: " + newObject.Values[0]);
返回空的。 如何通过索引号访问这些变量

提前谢谢。

你就快到了

由于Valuesarray类具有文本变量,因此代码应调用它:

    Debug.Log("Values: " + newObject.Values[0].Text);
    Debug.Log("Values: " + newObject.Values[1].Text);
    Debug.Log("Values: " + newObject.Values[2].Text);

非常感谢,成功了!我没想到会有这个解决方案,但它肯定会帮助我进一步开发脚本。@Hieronymus祝你的项目好运。干杯
    Debug.Log("Values: " + newObject.Values[0].Text);
    Debug.Log("Values: " + newObject.Values[1].Text);
    Debug.Log("Values: " + newObject.Values[2].Text);