我正在用Unity制作一款带有编辑器关卡的游戏,它将关卡数据写入。txt文件
我的问题是对文件的更改不能正确应用,因为我只有在重新启动游戏时才能看到它们。
当玩家创建一个新关卡时,我使用这个:
TextAsset txtFile = Resources.Load<TextAsset>("Levels");
StreamWriter streamWriter = new StreamWriter(new FileStream("Assets/Resources/" + levelsManager.filename + ".txt", FileMode.Truncate, FileAccess.Write));
在方法结束时,我关闭了StreamWriter。
streamWriter.Flush();
streamWriter.Close();
streamWriter.Dispose();
如果用户创建了多个级别,则只保存最后一个级别。
将文件模式更改为追加不起作用,因为在重新启动游戏并创建关卡后,它会再次创建存储的关卡。
¿有没有办法刷新文件,这样我就不必每次创建一个关卡都重新开始游戏了?
提前谢谢你。
你只需要在Unity中使用AssetDatabase.Refresh
来刷新资源。
当玩家创建一个新关卡时,我使用这个
请注意,这些在构建的应用程序中都不起作用!
构建应用程序后,Resources
是只读的。无论如何,最佳实践中的注释->资源
不要用!
您可能更愿意将默认文件存储在StreamingAssets
中并使用Application.streamingassetsPath
,然后在稍后的构建中使用Application.persistentDataPath
而不是回退到streamingAssetsPath
仅用于读取(再次StreamingAssets
在构建后是只读的)
例如
public string ReadlevelsFile()
{
try
{
#if UNITY_EDITOR
// In the editor always use "Assets/StreamingAssets"
var filePath = Path.Combine(Application.streamingAssetsPath, "Levels.txt");
#else
// In a built application use the persistet data
var filePath = Path.Combine(Application.persistentDataPath, "Levels.txt");
// but for reading use the streaming assets on as fallback
if (!File.Exists(filePath))
{
filePath = Path.Combine(Application.streamingAssetsPath, "Levels.txt");
}
#endif
return File.ReadAllText(filePath);
}
catch (Exception e)
{
Debug.LogException(e);
return "";
}
}
public void WriteLevelsFile(string content)
{
try
{
#if UNITY_EDITOR
// in the editor always use "Assets/StreamingAssets"
var filePath = Path.Combine(Application.streamingAssetsPath, "Levels.txt");
// mke sure to create that directory if not exists yet
if(!Directory.Exists(Application.streamingAssetsPath))
{
Directory.CreateDirectory(Application.streamingAssetsPath);
}
#else
// in a built application always use the persistent data for writing
var filePath = Path.Combine(Application.persistentDataPath, "Levels.txt");
#endif
File.WriteAllText(filePath, content);
#if UNITY_EDITOR
// in Unity need to refresh the data base
UnityEditor.AssetDatabase.Refresh();
#endif
}
catch(Exception e)
{
Debug.LogException(e);
}
}