# How to read a data from text file in unity

Can anybody help me out with giving the steps needed for reading data from the text file in unity and how can the script be added.

• Is the text file an Asset (part of your Unity project) or located on the file system? – Kelly Thomas Oct 13 '14 at 9:18
• its located on the filesystem.I have placed my file in E drive and used the following code  import System.IO; var filename="data.txt"; function Start () { var sourse=new StreamReader(Application.dataPath+"/" + filename); var fileContents=sourse.ReadToEnd(); sourse.Close(); var lines=fileContents.Split("\n"[0]); for(line in lines) { print(line); } }  – user1509674 Oct 13 '14 at 10:27
• VTC as not game specific. IO is generic programming, this should be on Stack Overflow, not GameDev. – Gnemlock Sep 25 '16 at 22:16
• The accepted answer isn't Unity specific, but the highest voted answer (which imo should have been accepted) is Unity specific. – jhocking Dec 6 '17 at 20:10

## C# Version.

using System.IO;

{

while(!inp_stm.EndOfStream)
{
// Do Something with the input.
}

inp_stm.Close( );
}


There's a class named TextAssets which is used for text file reading. http://docs.unity3d.com/Manual/class-TextAsset.html Here you can find the supported file format.

So if you want to read the text file, the script would be like this:

class YourClassName : MonoBehaviour{
public TextAsset textFile;     // drop your file here in inspector

void Start(){
string text = textFile.text;  //this is the content as string
byte[] byteText = textFile.bytes;  //this is the content as byte array
}
}


or you can read the text as resource like this:

TextAsset text = Resources.Load("YourFilePath") as TextAsset;

• Also worth mentioning that the TextAsset in question should probably be placed within the Assets/Resources folder. This is the most correct answer as all the other answers seem to ignore the fact that this is within Unity. They are correct ways of reading a file in C# but ignore things like cross-platform deployment and paths. – McAden Oct 26 '14 at 6:34
• If you use TextAsset you prob drag reference to a MonoBehaviour and use the yext property. In which case it does not need to be in Respurces – Rakka Rage Mar 7 '17 at 15:49

You can do this in the same way you would in .NET

string word = File.ReadAllText(txtFilePath);


This code snippet can be used in any location you wish then.

This code is working fine for me to read the content in the text file

import System.IO;

var filename="data.txt";

function Start () {