adr*_*ian 2 c# streamwriter unity-game-engine
我正在 Unity 中制作一个游戏,其编辑器关卡将关卡数据写入 .txt
\n我的问题是对文件的更改未正确应用,因为我只能在重新启动游戏时才能看到它们。
\n当玩家创建新关卡时,我使用以下命令:
\nTextAsset txtFile = Resources.Load<TextAsset>("Levels");\nStreamWriter streamWriter = new StreamWriter(new FileStream("Assets/Resources/" + levelsManager.filename + ".txt", FileMode.Truncate, FileAccess.Write));\nRun Code Online (Sandbox Code Playgroud)\n在该方法结束时,我关闭 StreamWriter。
\n streamWriter.Flush();\n streamWriter.Close();\n streamWriter.Dispose();\nRun Code Online (Sandbox Code Playgroud)\n此外,如果用户创建多个级别,则仅保存最后一个级别。
\n将文件模式更改为追加不起作用,因为重新启动游戏并创建关卡后,它还会再次创建存储的关卡。
\n\xc2\xbf有没有办法刷新文档,这样我就不必每次创建关卡时都重新启动游戏?
\n先感谢您。
\n您只需要使用 刷新 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);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
179 次 |
| 最近记录: |