Hi there i have one TXT hile and i wanna use it as one word with one number. Text file...
Character / 0934
US / 0424
Seoul / 0426
etc...
and i wanna read one line such as *"seoul, 0426"*
Hi there i have one TXT hile and i wanna use it as one word with one number. Text file...
Character / 0934
US / 0424
Seoul / 0426
etc...
and i wanna read one line such as *"seoul, 0426"*
Use the System.IO
classes, such as StreamReader:
import System.IO;
var fileName = "foo.txt";
function Start () {
var sr = new StreamReader(Application.dataPath + "/" + fileName);
var fileContents = sr.ReadToEnd();
sr.Close();
var lines = fileContents.Split("
"[0]);
for (line in lines) {
print (line);
}
}
This reads in the contents of the named text file and splits into separate strings on the newline char.
You can use the Unity Text Asset class, and then use a regex to split it.
Simply do this…
public TextAsset dictionaryTextFile;
and then literally drop your text file in to the project. It would be called something.txt. In the example it is called yourTextFIle.txt…
To convert a TextAsset
to one long string, is completely trivial.
You just go .text
. That’s all there is to it.
That’s exactly the reason we all use Unity, rather than actually bothering programming.
You then just convert that one long string to a List<>
of strings.
So, in your code, simply do this:
public TextAsset dictionaryTextFile;
private string theWholeFileAsOneLongString;
private List<string> eachLine;
void Start()
{
theWholeFileAsOneLongString = dictionaryTextFile.text;
eachLine = new List<string>();
eachLine.AddRange(
theWholeFileAsOneLongString.Split("
"[0]) );
// you're done.
Debug.Log(eachLine[4]);
Debug.Log(eachLine[10]);
Debug.Log(eachLine[101]);
Debug.Log(eachLine[0]);
int kWords = eachLine.Count;
Debug.Log(eachLine[kWords-1]);
}
AddRange
and .Split(" "[0])
are just methods to easily convert a long string
which is separated by newlines, to, a List<>
of words.
Fortunately it’s that easy.
You can use the standard c# file api.
If you want to run it in the webplayer or you are using javascript you could use the WWW class to do this.
var pathToFile = "path/to/example.txt";
var url = "file://" + pathToFile;
yiel download = new WWW(url);
text = download.data;
pathToFile needs to be a complete path. You could also use a path relative to your unity project. Then you'd have to do this to run in the editor:
var url = "file://" + Application.dataPath + "/../" + pathToFile;
How exactly would we open the file?