0

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]);
}
Black Frog
  • 11,595
  • 1
  • 35
  • 66
Unforgiven52
  • 41
  • 1
  • 5
  • 1
    My best guess is that `Resources.Load(filepath)` is returning null or it's not convertible to `TextAsset. Have you debugged? – Claudio Redi May 01 '15 at 01:40
  • 1
    possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – jdphenix May 01 '15 at 01:41
  • 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 May 01 '15 at 03:22

1 Answers1

0

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);
    }
}
Ming-Tang
  • 17,410
  • 8
  • 38
  • 76