unity3d 在Unity/C#中如何将json文件中的字符串打印到TMP_Text中?

xcitsw88  于 2023-01-21  发布在  C#
关注(0)|答案(1)|浏览(195)

我刚开始使用Unity和C#。我有一段代码是从一个读取json文件的源代码中获得的。我希望json文件中的数据显示并打印在特定的文本字段中。
这是我的代码...

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;

public class jsonReader : MonoBehaviour
{
    public TextAsset txtjson;

    public TMP_Text desc; //TextField Object in scene

    [System.Serializable]
    public class Question
    {
        public string questiondesc;
        public string answer1, answer2, answer3, answer4;
        public int correctans;
    }

    [System.Serializable]
    public class QuestionList
    {
        public Question[] questions; 
    }

    
    public QuestionList myQuestionList = new QuestionList(); //Loads Question Array

    void Start()
    {
        myQuestionList = JsonUtility.FromJson<QuestionList>(txtjson.text);
    }
}


下面是一个json示例...

{
    "questions": [
        {
            "questiondesc": "How tall is this... ?",
            "answer1": "1 inch",
            "answer2": "3 inches",
            "answer3": "7 inches",
            "answer4": "10 inches",
            "correctans": 1
        },

        {
            "questiondesc": "First letter of the english alphabet?",
            "answer1": "A",
            "answer2": "B",
            "answer3": "C",
            "answer4": "D",
            "correctans": 0
        }
    ]
}

例如,我希望json文件中的第一个问题描述加载到TMP_text对象中。

js81xvg6

js81xvg61#

我将通过几个步骤来帮助你澄清一些问题。你有一个问题列表,所以你需要用一个for循环或foreach循环抛出它们,然后访问你的描述文本,然后将它分配给你的文本UI。
string allDescriptions = "";

foreach (var q in myQuestionList)
    {
     allDescriptions += q.questiondesc+" \n";
    }
desc.text = allDescriptions;//this will display all the question descriptions

如果你想显示一个特定的问题描述,使一个函数,采取索引或id,然后像先生.@derHugo说,只需调用desc.text = myQuestionList.questions[someIndex].questiondesc,我会提供一个例子:

public void DisplayQuestionDescription(int index)
     {
        if (string.IsNullOrEmpty(myQuestionList.questions[index].questiondesc))
         {
                        desc.text = myQuestionList.questions[index].questiondesc;
         }
         else
         {
                        desc.text = "No Description";
         }
     }

要使用此功能,您只需调用DisplayQuestionDescription(0);(例如)来获取第一个问题的描述

相关问题