Loading JSON as a Text Asset using Resources.Load
Hey folks,
So I've got a bunch of .json files in my Resources folder, they are contained within several sub folders. And I want to Load them, before passing them through StreamReader and returning the final text.
However, when I try to Load the file I'm encountering a Null Ref of - "NullReferenceException: Object reference not set to an instance of an object"
Now I know this suggests the file isn't there but it is and I've got some Debug showing that the path is correct. Below is my code:
public static string LoadResourceTextfile(string path)
{
string text;
string filePath;
filePath = @"SetupData/" + path;
// filePath = filePath.Replace(".json", "");
Debug.Log("filePath Is: " + filePath);
var targetFile = Resources.Load<TextAsset>(filePath);
using (var streamReader = new StreamReader(targetFile.text, Encoding.UTF8))
{
text = streamReader.ReadToEnd();
}
return text;
}
The "filePath" mentioned above which is passed in actually has the .json suffix, which is why I have a commented out replace. But that didn't fix the issue in any case.
Suggestions would be very welcome :).
Answer by William_Goodspeed · Nov 04, 2015 at 10:30 AM
In the end I found that simple removing the StreamReader was the easiest way to solve my issues.
public static string LoadResourceTextfile(string path)
{
string filePath = "SetupData/" + path.Replace(".json", "");
TextAsset targetFile = Resources.Load<TextAsset>(filePath);
return targetFile.text;
}
Thanks! That's work for write and read json files :) you saved me too
Yeah, I had to remove the .json as well. None of the paths have a suffix in the documentation, so I guess that is a clue. https://docs.unity3d.com/ScriptReference/Resources.Load.html