對于我的游戲,我使用 PlayerPrefs 來存盤玩家的總體得分和每個級別的得分。在編輯器中,創建、更新和洗掉 PlayerPrefs 沒有問題。但是當我構建游戲時,問題開始出現。
PlayerPrefs 將照常創建和更新,但洗掉被破壞。
這是在按鈕中用于重置分數的代碼
public void ResetProgress()
{
foreach (string file in Directory.GetFiles(Application.persistentDataPath))
{
File.Delete(file);
}
PlayerPrefs.DeleteAll();
PlayerPrefs.Save();
}
在編輯器中,此按鈕將從注冊表中洗掉 PlayerPrefs(我使用 regedit 和資產商店中的插件來確保這一點)。但是在構建時,注冊表將保持不變,并且顯示這些 PlayerPrefs 提供的值的場景不會改變。
這是保存資料的代碼
string path = Application.persistentDataPath "/" levelName ".dat";
//Check if there is any save file to begin with
if(File.Exists(path))
{
File.AppendAllText(path, playerSolution Environment.NewLine);
string[] playerValues = PlayerPrefs.GetString(SceneManager.GetActiveScene().name).Split('-').ToArray();
PlayerPrefs.SetString(SceneManager.GetActiveScene().name, $"{int.Parse(playerValues[0]) 1}-{playerTime}");
}
else
{
File.WriteAllText(path, playerSolution Environment.NewLine);
PlayerPrefs.SetString(SceneManager.GetActiveScene().name, $"1-{playerTime}");
}
if(PlayerPrefs.HasKey("AllPlayerScore"))
{
PlayerPrefs.SetInt("AllPlayerScore", PlayerPrefs.GetInt("AllPlayerScore") 1);
}
else
{
PlayerPrefs.SetInt("AllPlayerScore", 1);
}
PlayerPrefs.Save();
And yes, I am aware that when you build a game, the registry directory will change. I've also tried to delete the registries to see if somehow my values are being cached, but no. Everything resets as expected.
Some final notes:
- The files that I create and delete are not connected to scores
- The logic from the button IS being called, because the files are being deleted
- The project is build in LTS version 2020.3.30f1
UPDATE 1: I have no clue why, but the problem was fixed in the button logic when I moved the PlayerPrefs.DeleteAll() to be executed before the file removal. I will keep the post open, so that someone far more knowledgeable can explain the issue.
uj5u.com熱心網友回復:
我將稱之為部分答案。PlayerPrefs.DeleteAll(); PlayerPrefs.Save();在某些情況下,當我重現此問題時,由于檔案拒絕洗掉導致跳過呼叫而導致的例外,該方法提前退出。
在 try/catch 塊中的呼叫可以解決這個特殊的原因。
public void ResetProgress()
{
foreach (string file in Directory.GetFiles(Application.persistentDataPath))
{
try
{
File.Delete(file);
}
catch {}
}
PlayerPrefs.DeleteAll();
PlayerPrefs.Save();
}
uj5u.com熱心網友回復:
這可能是一種預感,但我希望您注意以下內容,這是渴望發表評論:
\Windows和類 Unix系統之間的路徑分隔符不同/。當您進行跨平臺開發時,這可能會導致路徑不正確,從而導致無法加載資料。
為了克服這個問題,您應該盡可能使用Path.PathSeparator或Path.靜態函式。
所以:
string path = Application.persistentDataPath "/" levelName ".dat";
會成為:
string path = Application.persistentDataPath
Path.PathSeparator levelName ".dat";
請注意,您可能對Application.persistentDataPath變數有同樣的問題。
注意:正如 derHugo 提到的,更好的選擇是使用Path.Combine:
string path = Path.Combine(Application.persistentDataPath, levelName ".dat");
更多資訊,請參閱:
https://docs.microsoft.com/en-us/dotnet/api/system.io.path.combine?view=net-6.0
和
https://docs.microsoft.com/en-us/dotnet/api/system.io.path.pathseparator?view=net-6.0
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/438290.html
下一篇:雪碧在本地檔案夾中沒有顯示?
