假设有一个自定义初始化文件Myfile.txt,程序启动时需要读取。
1.请确保Myfile.txt的编码格式为UTF-8,否则会出现中文乱码。
2.将文件放在Assets\StreamingAssets目录下。
#if UNITY_EDITOR
string filepath = "file://"+Application.streamingAssetsPath+"/"+"Myfile.txt";
#elif UNITY_IPHONE
string filepath = Application.dataPath +"/Raw"+"/Myfile.txt";
#elif UNITY_ANDROID
string filepath = "jar:file://" + Application.dataPath + "!/assets/"+"Myfile.txt";
#endif
4.Windows平台下的.net dll库并不是都能在android、iOS上跨平台运行,因此,应尽量使用unity提供的标准类。比如,这里的读文件就不能使用File、StreamReader类(经测试这两个类在这里无法正常运行),而应该使用unity提供的WWW类。源代码如下:
public void OnClickBtn()
{
StartCoroutine(fun());
}
public IEnumerator fun()
{
#if UNITY_EDITOR
string filepath = "file://"+Application.streamingAssetsPath+"/"+"Myfile.txt";
#elif UNITY_IPHONE
string filepath = Application.dataPath +"/Raw"+"/Myfile.txt";
#elif UNITY_ANDROID
string filepath = "jar:file://" + Application.dataPath + "!/assets/"+"Myfile.txt";
#endif
WWW data = new WWW(filepath);
yield return data;
if(string.IsNullOrEmpty(data.error))
{
Text textCpnt = textCtrl.GetComponent();
textCpnt.text = data.text;
}
else
{
Text textCpnt = textCtrl.GetComponent();
textCpnt.text = data.error;
}
}