Application.streamingAssetsPath 和 WebGL 构建

Application.streamingAssetsPath and WebGL build

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

我正在根据脚本收到 "Cannot find file!" 消息:

    else if (!File.Exists (filePath))
    {
        Debug.LogError ("Cannot find file!"); 
    }

我得到了使用 WWW class 的答案,如 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);
    }
}

我很乐意这样做,但我对编码太陌生了,我需要一些解释。我现在的第一个问题是:行中的 "my file" 字符串是什么

    public string filePath = System.IO.Path.Combine(Application.streamingAssetsPath, "MyFile");

我应该在那里写什么?是 url 吗?如果它是 url,那么 url 是什么?

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

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

The first question I have for now is: what is this "my file" string in the line

这应该是 file.Although 的名称,但缺少扩展名。你应该补充一下。例如,.txt.jpgpng...

What am I supposed to write there? Is it a url? And if it is a url, the url of what?

您只需要写下 "MyFile" 扩展名的文件名即可。

示例使用:

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

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

public string filePath = System.IO.Path.Combine(Application.streamingAssetsPath, "Anne.txt");

现在假设“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");

就是这样。这里没有什么复杂的。然后将该路径字符串与 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);
}

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

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

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

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

您从文件夹中读取

您需要从服务器读取 webgl

WebGl 不会让你那样做。

这是建议

https://docs.unity3d.com/Manual/UnityWebRequest-RetrievingTextBinaryData.html