Unity 3D and Android, how to manipulate txt file?


How to do in Unity 3D read a arquivo txt line by line and store in a vector using C #.

Well, I was able to manipulate arquivo .txt , however in Android it does not work.

Follow the code I used.

int counter;
string line;
string[] teste = new string[10];
System.IO.StreamReader file;
file = new StreamReader("nome_do_arquivo.txt");

        while ((line = file.ReadLine()) != null)
             teste[counter] = line;



This code for pc solves my problem, however I need to Android , compiling to Android this method does not work, it's as if it does not take% along with .txt .

Another question, in Apk used Unity 3D to C# , how to manipulate txt files?     

asked by anonymous 03.01.2016 / 00:15

2 answers


See this example that does a line-by-line reading:

using UnityEngine;
using System.Collections;
using System;
using System.IO;

public class LineReader : MonoBehaviour
    protected FileInfo theSourceFile = null;
    protected StreamReader reader = null;
    protected string text = " "; // permite que a primeira linha seja lida

    void Start () {
        theSourceFile = new FileInfo ("nome_do_arquivo.txt");
        reader = theSourceFile.OpenText();

    void Update () {
        if (text != null) {
            text = reader.ReadLine();
            print (text);
07.01.2016 / 21:15

According to Documentation , you need a paste called Resources . >.


Pathname of the target folder. When using the empty string (i.e., ""),   the function will load the entire contents of the Resources folder.

Now with this procedure you should already be able to read the file on Android:

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;

And here at Unity Forum A question with a validated answer that can clarify some doubts!


Several ways to read each line of the file:

public TextAsset TextFile; //Com essa variavel você pode jogar o arquivo pelo Inspetor 
void readTextFileLines() { 
    string[] linesInFile = TextFile.text.Split('\n');

    foreach (string line in linesInFile) //Para cada linha....
        //Aqui você adiciona no seu vetor!

Similar to what you use (which would make it even easier for you to implement!):

using System.IO;

void readTextFile(string file_path)
   StreamReader inp_stm = new StreamReader(file_path);

       string inp_ln = stm.ReadLine( );
       // Do Something with the input. 

   inp_stm.Close( );  

And so it goes ...

05.01.2016 / 01:34