2015-05-01 185 views
0

我一直在嘗試從.JSON文件中檢索一些數據。即時通訊目前使用Unity與SimpleJson,當我加載了比賽,我得到這個錯誤:從資源加載文本文件

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)

這裏是代碼:

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

我最好的猜測是,'Resources.Load(文件路徑)'將返回null或它不是轉換爲'TextAsset。你調試過了嗎? –

+1

[什麼是NullReferenceException,我該如何解決它?]的可能重複(http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – jdphenix

+0

93線在哪裏? –

回答

0

Resources.load僅適用於在資源文件夾中。嘗試將文件listofgames.txt移動到Resources文件夾(如果需要,請創建它),然後撥打Resources.load("listofgames")(您必須省略文件擴展名)。

請注意,您也可以有TextAsset字段,以便您可以在檢查員中參考它。這適用於TextAsset的資源之外:

using UnityEngine; 
using System.Collections; 

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