I'm trying to read a text file in Unity. I have problems.
In desktop, when I generate the Stand Alone, I need to copy manually the text file. I don't know how include inside my application.
In web application (and Android), I copy the file manually but my game can't find it.
This is my "Read" code:
public static string Read(string filename) {
//string filePath = System.IO.Path.Combine(Application.streamingAssetsPath, filename);
string filePath = System.IO.Path.Combine(Application.dataPath, filename);
string result = "";
if (filePath.Contains("://")) {
// The next line is because if I use path.combine I
// get something like: "http://bla.bla/bla\filename.csv"
filePath = Application.dataPath +"/"+ System.Uri.EscapeUriString(filename);
//filePath = System.IO.Path.Combine(Application.streamingAssetsPath, filename);
WWW www = new WWW(filePath);
int timeout = 20*1000;
while(!www.isDone) {
System.Threading.Thread.Sleep(100);
timeout -= 100;
// NOTE: Always get a timeout exception ¬¬
if(timeout <= 0) {
throw new TimeoutException("The operation was timed-out ("+filePath+")");
}
}
//yield return www;
result = www.text;
} else {
#if !UNITY_WEBPLAYER
result = System.IO.File.ReadAllText(filePath);
#else
using(var read = System.IO.File.OpenRead(filePath)) {
using(var sr = new StreamReader(read)) {
result = sr.ReadToEnd();
}
}
#endif
}
return result;
}
My questions are:
How can I include my "text file" as a Game Resource?
Is something wrong on my code?
Unity offers a special folder called Resources where you can keep files and load them at runtime through Resources.Load
Create a folder called Resources in your project, and put your files in it (in this case, you text file).
Here's an example. It assumes that you're sticking your file straight into the Resources folder (not a subfolder in Resources)
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;
}