gpt4 book ai didi

c# - 在我重新启动游戏之前,streamWriter 不会应用更改

转载 作者:行者123 更新时间:2023-12-02 15:52:53 24 4
gpt4 key购买 nike

我正在 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();

此外,如果用户创建了多个关卡,则只保存最后一个关卡。

将文件模式更改为 apend 不起作用,因为在重新启动游戏并创建关卡后,它还会再次创建存储的关卡。

¿是否有一种刷新文档的方法,这样我就不必在每次创建关卡时都重新启动游戏?

提前谢谢你。

最佳答案

您只需要使用 AssetDatabase.Refresh 刷新 Unity 中的资源.


但是

When the player creates a new level i use this

请注意,这些都不适用于构建的应用程序!

构建应用后,Resources只读。无论如何请注意Best practices -> Resources

Don't use it!

您可能更愿意将默认文件存储在 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);
}
}

关于c# - 在我重新启动游戏之前,streamWriter 不会应用更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72056470/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com