统一在文本框中显示json个结果

Display json result in textbox in unity

我有一个统一的脚本,它搜索一个 json 文件并将 RawImage 的纹理更改为在搜索的相应结果中找到的 url 图片地址。 我现在还想更改文本框中的文本以显示另一个字段结果。

我用来搜索和更改图像的代码是

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

public class UrlOpener : MonoBehaviour
{
public RawImage rawImage;
public InputField SearchBox;
public int displayIndex;
List<ArtImage> result;
public void Open()
{
    Debug.Log("start");
    rawImage.color = Color.white;

    //string imageaddress;
    using (StreamReader r = new StreamReader("Assets/run_results-2.json"))
    {
        string json = r.ReadToEnd();

        ArtImages imgs = JsonUtility.FromJson<ArtImages>(json);
        result = new List<ArtImage>();
        if (imgs.artwork.Length > 0)
        {
            foreach(ArtImage img in imgs.artwork)
            {
                if (img.name.ToLower().Contains(SearchBox.text.ToLower()))
                {
                    result.Add(img);


                    //StartCoroutine(applytexture(imageaddress,img.heightimg,img.widthimg)); // execute the section independently
                    //break;
                }
                                }
            if (result.Count > 0)
            {
                StartCoroutine(applytexture(result[0].image,result[0].heightimg,result[0].widthimg)); // execute the section independently
                displayIndex = 0;
            }


            // the following will be called even before the load finished
        }
    }
}

private IEnumerator applytexture(string imageaddress, float heightimg,float widthimg)
{


    Debug.Log("Loading ....");
    WWW wwwLoader = new WWW(imageaddress);   // create WWW object pointing to the url
    yield return wwwLoader;         // start loading whatever in that url ( delay happens here )

    Debug.Log("Loaded");
    rawImage.color = Color.white;              // set white
    rawImage.texture = wwwLoader.texture;
    GetComponent<RectTransform>().sizeDelta = new Vector2(widthimg,heightimg);

}

}




[Serializable]
public class ArtImage
{
public string name;
public string image;
public float widthimg;
public float heightimg;
}
[Serializable]
public class ArtImages
{
public ArtImage[] artwork;
}

我需要一个文本框来显示相同​​结果的 "name" 字段中存储的内容。

如有任何帮助,我们将不胜感激。

快速说明,我是 C# 的初学者,所以请尝试以我理解的方式回复哈哈

干杯

要显示结果,您可以通过两种方式直接读出值并显示 Json 数据,或者您可以读出它然后直接显示您的数据保持 class 中的值

public void LoadGameData()
{
    if (File.Exists(filePath))
    {
        string dataAsJson = File.ReadAllText(filePath);
        jsonDataClass = JsonUtility.FromJson<JsonDataClass>(dataAsJson);
        text.text = dataAsJson;
    }
    else
    {
        text.text = "No JsonFile found";
    }
}

在使用这个之前,你需要有一个数据保存 class(用它替换 JSONDataClass)然后你需要一个 public 文本文本,这是你的文本框来显示 Json中的数据。 最后请注意,您需要将文件路径替换为您的 Json 文件路径。

如果您对该主题有更多问题,我建议您查看:Unity Json reader and Unity textfield Documentation