Reading a text file from asset folder

Hi All,
I want to read a .txt file which is stored in the asset folder of the game. So for that i tired using both FileInfo and StreamReader. If m right for both these classes I have to pass the filepath as parameter. Thus, the param I passed was -

Application.datapath + “/1.txt” (1.txt being my text file and datapath gives me < …/Appname.app/Data>). However, if i go in the Data folder ( via Finder ) I do not see any such file but few compressed and encoded files by unity and it gives me a runtime error -
“DirectoryNotFoundException: Could not find a part of the path…”

So, in short I wanna know how to read a file which is stored in the Asset folder.

Also, if possible can anyone tell me how to give text file’s name to the TextAsset class?

Thanks

An asset in the Asset folder is not stored in a separate file, it’s compiled together with all the other assets for that level, and therefore you can’t access it or read it. Just use TextAsset in this case; you don’t need to use StreamReader or any other file I/O. Simply use it like any other asset (i.e., drag it onto a public variable).

–Eric

Thanks for the reply. However my problem is that it’s not just one text file. I have one text file for each level of the game - a kind of predefined values stored in them. So I was planning to have one class for reading the files and using it in each level class.

If you save the text files as Resources instead you can just load them into TextAssets by

TextAsset textFile = (TextAsset)Resources.Load(“myTextFile”), typeof(TextAsset));

2 Likes

Hi I tried that too. I kept a file named 1.txt in the asset folder. and tried reading it using the same method which you have specified. However, it gives me a

“NullReferenceException: Object reference not set to an instance of an object…” error.

Make sure you put your text file in the ‘Assets/Resources’ folder of your project. Then use something like this (javascript):

var tempAsset: TextAsset = Resources.Load(“1”, TextAsset);
var myString: String = tempAsset.text;

3 Likes

hey thanks a ton. it worked out. I never knew that we have to keep that in “resources” folder. thanks to all for the help.