【问题标题】:Loading Text File From Resource从资源加载文本文件
【发布时间】:2015-05-01 01:37:43
【问题描述】:

我一直在尝试从 .JSON 文件中检索一些数据。我目前正在将 Unity 与 SimpleJson 一起使用,当我加载游戏时出现此错误:

NullReferenceException:对象引用未设置为 对象 PlayerInteraction.test () (在 Assets/Scripts/PlayerInteraction.cs:93) PlayerInteraction.Start () (在 资产/脚本/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]);
}

【问题讨论】:

  • 我最好的猜测是 Resources.Load(filepath) 正在返回 null 或者它不能转换为 `TextAsset.你调试了吗?
  • 已解决,我已经阅读了 Resources.Load 并且它只从资源文件夹中获取文件(我知道但仍然没有工作)。除此之外,您不应该使用“.txt”或“.JSON”作为后缀,而只是文件名。不过谢谢你的帮助

标签: c# json unity3d


【解决方案1】:

Resources.load 仅适用于 Resources 文件夹中的文件。尝试将您的文件 listofgames.txt 移动到 Resources 文件夹(如果需要,创建它),然后调用 Resources.load("listofgames")(您必须省略文件扩展名)。

请注意,您还可以拥有TextAsset 字段,以便您可以在检查器中引用它。这适用于资源之外的TextAssets:

using UnityEngine;
using System.Collections;

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-30
    • 2014-04-19
    • 2016-09-02
    • 1970-01-01
    相关资源
    最近更新 更多