【发布时间】:2018-08-22 20:06:55
【问题描述】:
我正在使用 Unity 3D 和 C# 开发一个包含多个迷你游戏的大型应用程序界面,该应用程序在应用程序的开头提供了一个登录页面。登录页面允许用户输入新的用户名,然后将其保存,或者从下拉列表中加载现有的用户名。我不需要密码,所以我只是将用户名保存到纯文本文件中。
为了在 Android 上保存,我使用的是 Application.persistentDataPath。以前,这工作得很好。然而,在过去的几周里,这种情况突然发生了变化。在设备上,项目仍然可以创建文件,但无法从中加载。每次显示的用户名都是空白的。我仍然可以手动检查文件是否存在并验证用户名是否保存到其中。
// Use this for initialization
void Start () {
f = new FileInfo(Application.persistentDataPath + @"\save.txt");
Load(); //Load existing username options here (if they exist)
Save();
Load();
selectedUsername.RefreshShownValue();
}
//Saves the list of entered usernames to a text file, placed in the persistent data path (which is different per platform)
void Save()
{
Debug.Log("Entered save function");
StreamWriter w = new StreamWriter(Application.persistentDataPath + @"\save.txt", false);
for (int i = 0; i < menuOptions.Count; i++)
{
w.WriteLine(menuOptions[i]);
}
w.Close();
}
//Reads the text file from the persistent data path, places usernames into a usable list
void Load()
{
f = new FileInfo(Application.persistentDataPath + @"\save.txt");
if (f.Exists && selectedUsername != null) //don't know why selectedUsername sometimes comes up as null, but that additional condition was needed
{
selectedUsername.ClearOptions();
selectedUsername.AddOptions(new List<string> { "" });
StreamReader r = new StreamReader(Application.persistentDataPath + @"\save.txt");
string line;
menuOptions.Clear();
while ((line = r.ReadLine()) != null)
{
menuOptions.Add(line);
selectedUsername.AddOptions(new List<string> { line });
}
selectedUsername.RefreshShownValue();
r.Close();
}
}
【问题讨论】:
-
从调试代码开始,发生了什么?添加一些 Debug.Log 行以检查发生了什么,或逐步执行代码。
-
我能够找出导致问题的原因,这是我正在使用的另一个插件。我相信它会导致事情被搁置,或者导致加载错过时间。我移动了插件的函数调用,它似乎修复了它。因此,在 Android 上保存不再有任何问题,并且 PersistentDataPath 似乎工作正常。
标签: android unity3d save text-files filepath