我在 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();
此外,如果用戶創建多個級別,則僅保存最后一個。
將檔案模式更改為附加不起作用,因為在重新啟動游戲并創建關卡后,它還會再次創建存盤的關卡。
? 有沒有辦法重繪 檔案,這樣我就不必每次創建關卡時都重新開始游戲了?
先感謝您。
uj5u.com熱心網友回復:
您只需要在 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);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/467728.html