我想从JSON文件中读取字符串并将其传递给我的UI在Unity中的文本我面临的问题是字符串始终为空, m不知道为什么,现在我找到JSON文件路径并阅读它,但是当我尝试访问字符串时它是空的。我不确定如何阅读json。我真的不明白这是如何工作的。我是JSON格式的新手,我正在尝试练习它。这是我的第一个方法。我使用Unity引擎,和我读使用流媒体资产统一:无法从JSON文件中读取字符串
读取数据从Json的脚本JSON文件:
using UnityEngine;
using System.IO;
public class ReadFromJson : MonoBehaviour {
private string _filePath = "myText.json";
Data dh;
string str;
void Start()
{
LoadGameData();
}
public Data getCurrentRoundData()
{
return dh;
}
private void LoadGameData()
{
string filePath = Path.Combine(Application.streamingAssetsPath, _filePath);
if (File.Exists(filePath))
{
string dataAsJSON = File.ReadAllText(filePath);
DataHolder loadedData = JsonUtility.FromJson<DataHolder>(dataAsJSON);
dh = loadedData.data;
str = loadedData.data.TextToPass;
Debug.Log("My Text is" + dh.TextToPass);
Debug.Log("Path Exist");
}
else
{
Debug.LogError("CANNOT LOAD GAME DATA!!");
}
}
}
经理的JSON数据适用于我的UI文本
DataController = FindObjectOfType<ReadFromJson>();
_data = DataController.getCurrentRoundData();
myText.text = _data.TextToPass;
DataHolder.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class DataHolder {
public Data data;
}
JSON文本
{"DataHolder":
{
"TextToPass":"I'm A Horse"
}
}
Data.cs
[System.Serializable]
public class Data {
public string TextToPass ;
}
我所得到的是TextToPass为null
你能分享你的DataHolder模型吗? – mindOfAi
是检查更新问题 – Nanopl
您的问题缺乏这么多的东西。你需要发布你正在阅读的json文件。 File.Exists是否返回true?什么是“TextToPass”?你可以看到如何阅读Unity中的json [here](https://stackoverflow.com/questions/36239705/serialize-and-deserialize-json-and-json-array-in-unity/36244111#36244111)。看起来你想用Json保存GameData。我为[这里](http://stackoverflow.com/a/40966346/3785314)做了一个帮助类。 – Programmer