我正在用一个在.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();
此外,如果用户创建多个级别,则只保存最后一个级别。
将文件修改为附件不起作用,因为在重新启动游戏并创建一个级别之后,它还会再次创建存储级别。
是否有一种刷新文档的方法,使我不必每次创建一个级别时都重新启动游戏?
提前谢谢你。
发布于 2022-04-29 02:33:42
您只需要使用AssetDatabase.Refresh
来刷新Unity中的资产。
然而,
当玩家创建一个新的级别时,我使用
请注意,所有这些都不会在构建的应用程序中工作!
在构建应用程序之后,Resources
是只读。无论如何,来自Best practices -> 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);
}
}
https://stackoverflow.com/questions/72056470
复制