【问题标题】:Acces array variables from a json file in Unity从 Unity 中的 json 文件访问数组变量
【发布时间】:2020-10-13 15:09:43
【问题描述】:

我正在尝试读取在 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;
    }
}

这是json读取文件的格式:

{"Values":[{
"Text":"A"
},
{
"Text":"B"
},
{
"Text":"C"
},
{
"Text":"D"
},
{
"Text":"E"
}]
}

检查读取和写入另一个文件。输出:

{"Values":[{"Text":"A"},{"Text":"B"},{"Text":"C"},{"Text":"D"},{"Text":"E"}]}

到目前为止一切都很好,但我不明白如何通过索引号读取各个变量,如下所示:

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

返回空。 如何通过索引号访问这些变量?

提前致谢。

【问题讨论】:

    标签: c# json unity3d


    【解决方案1】:

    你快到了!

    由于您的 Valuesarray 类有 Text 变量,您的代码应该调用它:

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

    【讨论】:

    • 非常感谢,它成功了!我没想到这个解决方案,但它肯定有助于我进一步开发脚本。
    • @Hieronymus 祝您的项目好运。干杯!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-01
    • 1970-01-01
    • 2019-04-02
    • 1970-01-01
    相关资源
    最近更新 更多