Read text file that is included in the project

I’ve been having some problems reading from a text file that is included in the project, because I can’t figure out how to do it :slight_smile:

I have text file in the root of my project. When playing in the editor in Windows everything works fine. When trying to play a build on an Android device, the file can’t be found.

	void Start () 
    {
        string fileLocation = Application.persistentDataPath + "file.txt";

        if (File.Exists(fileLocation))
        {
            // STUFF HAPPENS HERE
        }
        else
        {
            Debug.LogError("Can't find file");
        }
    }

According to logcat, the Android app is looking for the file here:

but when I use ES Explorer there isn’t a file there.

So I’m wondering what I need to do in order to make the Android build find the text file.

You should probably put the file in the streamed assets folder. I believe this makes it so that it is stored inside the apk itself.
Or you can store it in the resources folder, which allows you Load the resource at runtime and since it is a text file you can then read the text file itself.

I’m not really having any luck with Resources.Load or streamed assets.

Do you know what exactly you need to load the text file as? The documentation says things like

go.renderer.material.mainTexture = Resources.Load("glass") as Texture;

How would you do this with a text file? Resources.Load returns an object by default, to what kind of thing do I need to cast it?

Reading text file “readme.txt” from the \Resources folder:

TextAsset txt = (TextAsset)Resources.Load("readme", typeof(TextAsset));
string content = txt.text;
4 Likes

Use a TextAsset public variable and link it in the inspector.

public TextAsset textFile;

–Eric

5 Likes

Thanks for clearing that up for me. I’ve got it working now. For anyone else looking at this in the future, keep in mind that you shouldn’t specify the extension of the file in the resources folder. “readme.txt” doesn’t work, but just “readme” (obviously) does.

Thanks nikolic!

1 Like

Good advice thanks!

I have this problem too but Unity gives me every time errors so can someone give me a sample project?

Perfect! thanks for the code sample, exactly what I needed.

Very helpful, thanks

OMG thanks you so much. The .txt at the end was causing the issue.
Fixed all my problems. Thanks so much.

Wonder what is the oldest comment you ever posted that I liked. Gotta be pushing a decade Eric. My shocking memory (and need to wear 17 other hats) doffs a dusty cap

EDIT: You would have loved the streamerReader implementation I just ripped, reading hard coded names WITH hard coded paths into a list of strings (that didn’t even point to the right place when built) - that is wiped 10000 times and one word is chosen from it on each cycle…

Are there words? yes, “improved on that”…