Application.streamingAssetsPath 和 WebGL 构建

3 c# json unity-game-engine unity-webgl

在我正在处理的项目中,StreamingAssets 目录中有两个 json 文件。处理它们的脚本在独立 PC 构建中完美运行,但在 WebGL 构建中根本不起作用。

我收到“找不到文件!” 根据脚本发送消息:

    else if (!File.Exists (filePath))
    {
        Debug.LogError ("Cannot find file!"); 
    }
Run Code Online (Sandbox Code Playgroud)

我得到了使用 WWW 类的答案,如 Unity Technologies 站点上的脚本 API 中所述,地址为:https ://docs.unity3d.com/ScriptReference/Application-streamingAssetsPath.html

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {
    public string filePath = System.IO.Path.Combine(Application.streamingAssetsPath, "MyFile");
    public string result = "";
    IEnumerator Example() {
        if (filePath.Contains("://")) {
            WWW www = new WWW(filePath);
            yield return www;
            result = www.text;
        } else
            result = System.IO.File.ReadAllText(filePath);
    }
}
Run Code Online (Sandbox Code Playgroud)

我很乐意这样做,但我在编码方面太新了,我需要一些解释。我现在的第一个问题是:该行中的“我的文件”字符串是什么

    public string filePath = System.IO.Path.Combine(Application.streamingAssetsPath, "MyFile");
Run Code Online (Sandbox Code Playgroud)

我应该在那里写什么?是一个网址吗?如果是 url,那么 url 是什么?

如果有人能握住我的手并引导我理解这一点,我将非常感激!谢谢你!

(这是我的第一个问题;我希望我没有犯错误,因为我还不知道这个地方是如何运作的。)

Pro*_*mer 5

我现在的第一个问题是:该行中的“我的文件”字符串是什么

这应该是文件的名称。尽管如此,它缺少扩展名。你应该补充一下。例如,.txt.jpgpng ....

我应该在那里写什么?是一个网址吗?如果是 url,那么 url 是什么?

您只需在“MyFile”所在的位置写入带有扩展名的文件名。

使用示例:

在您的项目中,您创建一个名为“ StreamingAssets ”的文件夹。

假设您有一个名为“Anne.txt”的文件,并且该文件位于 “StreamingAssets”内。文件夹,这应该是你的路径:

public string filePath = System.IO.Path.Combine(Application.streamingAssetsPath, "Anne.txt");
Run Code Online (Sandbox Code Playgroud)

现在假设“ Anne.txt ”文件夹放置在名为“ Data ”的文件夹中,然后该文件夹位于“ StreamingAssets ”文件夹中,它应该如下所示:“ StreamingAssets/Data/Anne.txt ”。

你的路径应该是:

public string filePath = System.IO.Path.Combine(Application.streamingAssetsPath, "Data");
filePath = System.IO.Path.Combine(filePath , "Anne.txt");
Run Code Online (Sandbox Code Playgroud)

就是这样。这里没什么复杂的。然后,您可以将该路径字符串与 一起使用WWW

也是你 if (filePath.Contains("://"))应该的if (filePath.Contains ("://") || filePath.Contains (":///"))

编辑

如果您要加载多个文件,我将该函数简化为此函数,以便它将文件名作为参数。

IEnumerator loadStreamingAsset(string fileName)
{
    string filePath = System.IO.Path.Combine(Application.streamingAssetsPath, fileName);

    string result;
    if (filePath.Contains("://") || filePath.Contains(":///"))
    {
        WWW www = new WWW(filePath);
        yield return www;
        result = www.text;
    }
    else
        result = System.IO.File.ReadAllText(filePath);
}
Run Code Online (Sandbox Code Playgroud)

现在,假设您在“ StreamingAssets ”文件夹中放置了 3 个名为“ Anne.txt ”、“ AnotherAnne.txt ”和“ OtherAnne.txt ”的文件,您可以使用以下代码加载它们:

StartCoroutine(loadStreamingAsset("Anne.txt"));

StartCoroutine(loadStreamingAsset("AnotherAnne.txt"));

StartCoroutine(loadStreamingAsset("OtherAnne.txt"));
Run Code Online (Sandbox Code Playgroud)