统一:Resources.Load 不工作
Unity: Resources.Load is not working
string filePath = "hfba_25";
TextAsset textAsset = Resources.Load(filePath) as TextAsset;
string fileString = textAsset.text;
我似乎无法弄清楚为什么资源不会在编辑器中加载,也不会在 android 设备上加载?文件 hfba_25
位于文件夹 Assets > Resources > hfba_25
Edit_1:textAsset 始终返回为 NULL
如果 textAsset
总是 null
,它可能意味着两件事(根据您的代码):
- 文件
hfba_25
在 Resources
子目录中不存在;
- 该文件确实存在,但不能转换为
TextAsset
。
要检查两者中哪一个是正确的,您需要将代码更改为:
TextAsset textAsset = (TextAsset)Resources.Load(filePath);
Debug.Log(textAsset);
然后 运行 在 Unity 中检查控制台。
如果你只是得到Null
,那么说明它是1(文件不存在)。
如果您得到的是 InvalidCastException: Specified cast is not valid.
,则表示它是 2,文件存在但不能转换为 TextAsset
类型。
发生这种情况是因为在 C# 中,如果您使用关键字 as
进行强制转换,当强制转换无效时您不会得到异常,而是将引用设置为 null
。
string filePath = "hfba_25";
TextAsset textAsset = Resources.Load(filePath) as TextAsset;
string fileString = textAsset.text;
我似乎无法弄清楚为什么资源不会在编辑器中加载,也不会在 android 设备上加载?文件 hfba_25
位于文件夹 Assets > Resources > hfba_25
Edit_1:textAsset 始终返回为 NULL
如果 textAsset
总是 null
,它可能意味着两件事(根据您的代码):
- 文件
hfba_25
在Resources
子目录中不存在; - 该文件确实存在,但不能转换为
TextAsset
。
要检查两者中哪一个是正确的,您需要将代码更改为:
TextAsset textAsset = (TextAsset)Resources.Load(filePath);
Debug.Log(textAsset);
然后 运行 在 Unity 中检查控制台。
如果你只是得到Null
,那么说明它是1(文件不存在)。
如果您得到的是 InvalidCastException: Specified cast is not valid.
,则表示它是 2,文件存在但不能转换为 TextAsset
类型。
发生这种情况是因为在 C# 中,如果您使用关键字 as
进行强制转换,当强制转换无效时您不会得到异常,而是将引用设置为 null
。