Unity — Чтение текстовых файлов (Android и веб-плеер)

Я пытаюсь прочитать текстовый файл в Unity. У меня проблемы.

  1. На рабочем столе, когда я создаю Stand Alone, мне нужно вручную скопировать текстовый файл. Я не знаю, как включить в мое приложение.

  2. В веб-приложении (и 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. Что-то не так в моем коде?


person lcnvdl    schedule 19.01.2015    source источник
comment
Вы добавили разрешение READ_EXTERNAL_STORAGE к файлу AndroidManifest.xml?   -  person Willis    schedule 19.01.2015


Ответы (1)


Unity предлагает специальную папку под названием Resources, где вы можете хранить файлы и загружать их во время выполнения с помощью Resources.Load.

Resources.Load в документах Unity

Создайте папку под названием 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;
}
person Venkat at Axiom Studios    schedule 20.01.2015
comment
Большое спасибо! Это как раз то, что мне было нужно! :D - person lcnvdl; 23.01.2015