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

时间:2019-11-21 11:24:45

标签: c# json unity3d search textbox

我有一个统一的脚本,该脚本搜索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;
}

我需要在文本框中显示存储在同一结果的“名称”字段中的内容。

任何帮助将不胜感激。

一个简短的说明,我是C#的初学者,因此请尝试以一种ID理解哈哈的方式做出回应

欢呼

1 个答案:

答案 0 :(得分:0)

要显示结果,有两种方法可以读出值并直接显示Json数据,也可以读出来然后直接从数据保存类中显示值

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";
    }
}

在使用此方法之前,您需要有一个数据保存类(用它替换JSONDataClass),然后需要一个公共Text文本,它是您的文本框,用于显示Json数据。 最后,您需要用Json文件路径替换文件路径。

如果您对热门话题还有其他疑问,建议您查看:Unity Json readerUnity textfield Documentation

相关问题