android - Unity - 读取文本文件(Android 和网络播放器)

标签 android unity-game-engine filereader unity-web-player

我正在尝试在 Unity 中读取文本文件。我有问题。

  1. 在桌面上,当我生成 Stand Alone 时,我需要手动复制文本文件。我不知道如何包含在我的应用程序中。

  2. 在 Web 应用程序(和 Android)中,我手动复制文件但我的游戏找不到它。

这是我的“读取”代码:

public static string Read(string filename) {

        //string filePath = System.IO.Path.Combine(Application.streamingAssetsPath, filename);
        string filePath = System.IO.Path.Combine(Application.dataPath, filename);
        string result = "";

        if (filePath.Contains("://")) {

            // The next line is because if I use path.combine I
            // get something like: "http://bla.bla/bla\filename.csv" 
            filePath = Application.dataPath +"/"+ System.Uri.EscapeUriString(filename);
            //filePath = System.IO.Path.Combine(Application.streamingAssetsPath, filename);

            WWW www = new WWW(filePath);

            int timeout = 20*1000;

            while(!www.isDone) {
                System.Threading.Thread.Sleep(100);
                timeout -= 100;

                // NOTE: Always get a timeout exception ¬¬
                if(timeout <= 0) {
                    throw new TimeoutException("The operation was timed-out ("+filePath+")");
                }
            }

            //yield return www;
            result = www.text;
        } else {

        #if !UNITY_WEBPLAYER
            result = System.IO.File.ReadAllText(filePath);
        #else
            using(var read = System.IO.File.OpenRead(filePath)) {
                using(var sr = new StreamReader(read)) {
                    result = sr.ReadToEnd();
                }
            }
        #endif

        }

        return result;
    }

我的问题是:

  1. 如何将我的“文本文件”包含为游戏资源?

  2. 我的代码有问题吗?

最佳答案

Unity 提供了一个名为Resources 的特殊文件夹,您可以在其中保存文件并在运行时通过Resources.Load 加载它们

Resources.Load on Unity docs

在您的项目中创建一个名为 Resources 的文件夹,并将您的文件放入其中(在本例中,您是文本文件)。

这是一个例子。它假定您将文件直接粘贴到 Resources 文件夹中(而不是 Resources 中的子文件夹)


public static string Read(string filename) {
    //Load the text file using Reources.Load
    TextAsset theTextFile = Resources.Load<TextAsset>(filename);

    //There's a text file named filename, lets get it's contents and return it
    if(theTextFile != null)
        return theTextFile.text;

    //There's no file, return an empty string.
    return string.Empty;
}

关于android - Unity - 读取文本文件(Android 和网络播放器),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28031091/

相关文章:

java - 一个界面,多个听众

c# - Unity3D 中的 Encoding.UTF32.GetBytes 返回额外的零

C# 条件不触发

unity-game-engine - 如何安全存储有关应用内购买/Unity3D 的信息

java - 需要帮助逐行读取文件

java - 如果一个线程关闭流而另一个线程开始从流中读取,我得到 "Stream closed exception"。如何解决这个问题?

android - App连接云端用了多少手机流量

java - 将字符串转换为颜色 int

android - 如何获取 'Google Play Developer Console' 中显示的设备型号?

javascript - Web Audio API getFloatFrequencyData 函数将 Float32Array 参数数据设置为 -Infinity 值数组