0
votes

i've been trying to retrieve some data from a .JSON file. Im currently using Unity with SimpleJson and when I load up the game i get this error:

NullReferenceException: Object reference not set to an instance of an object PlayerInteraction.test () (at Assets/Scripts/PlayerInteraction.cs:93) PlayerInteraction.Start () (at Assets/Scripts/PlayerInteraction.cs:23)

here is the code:

void test(){
    string filepath = (Application.dataPath + "/listofgames.txt");
    TextAsset file = Resources.Load(filepath) as TextAsset;
    var node = JSON.Parse(file.text); //line 93
    var pl = node["apps"];
        Debug.Log("TEST: " + pl[0]);
}
1
My best guess is that Resources.Load(filepath) is returning null or it's not convertible to `TextAsset. Have you debugged? - Claudio Redi
Solved, i've read up on Resources.Load and it only grabs files from the resources folder ( i knew that but still didn't work). ALong with that you're not supposed to use ".txt" or ".JSON" as a suffix, just the file name. But thank you for the help - Unforgiven52

1 Answers

0
votes

Resources.load only works for files in Resources folder. Try to move your file listofgames.txt to the Resources folder (create it if you need), then call Resources.load("listofgames") (you must omit file extension).

Please note you can also have TextAsset fields so you can reference to it in the inspector. This works with TextAssets outside of Resources:

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {
    public TextAsset asset;
    void Start() {
        print(asset.text);
    }
}