i'm trying to read stringfrom json file and pass it to my UI Text in Unity, The issue i'm facing is that the string is always null and i'm not sure why, Right now i find the JSON file path and read it, but when i try to access the string it's null. i'm not sure how to read the json. I really don't understand how this all works. i'm new to JSON format and i'm trying to practice it. This is my first approach. i'm using Unity Engine, and i'm reading the json file using Streaming Assets
Read Data from Json Script:
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!!");
}
}
}
Manager that applies the json data to my UI Text
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 Text
{"DataHolder":
{
"TextToPass":"I'm A Horse"
}
}
Data.cs
[System.Serializable]
public class Data {
public string TextToPass ;
}
What i get is TextToPass is null