這是由克里斯的評論回答的。
我還必須做equipedShield = stateVariables.equipedShield; equipedWeapon = stateVariables.equipedWeapon; healthPotionCount = stateVariables.healthPotionCount; playerExpEarned = stateVariables.playerExpEarned;
才能讓它加載,謝謝克里斯。
我的問題是我可以使用變數名來存盤值嗎?還是必須是實際數字?
我在這里找到了一篇文章C# - Saving Console Game Values 我選擇進行序列化,而是保存在我的檔案中,這樣我實際上可以找到要加載到 main 中的 txt 檔案(我確實找到了):
string folder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
folder = Path.Combine(folder, "RNGgameSaveFiles");
Directory.CreateDirectory(folder);
string dataFile = Path.Combine(folder, "RNGgameSaveFileV1");
if (File.Exists(dataFile))
{
using (Stream stateStream = File.OpenRead(dataFile))
{
BinaryFormatter deserializer = new BinaryFormatter();
stateVariables = (AppState)deserializer.Deserialize(stateStream);
}
}
它似乎保存得很好,但是加載時一切都是空的。
喜歡 :
static int roundsPlayed;
static decimal money = 0;
static decimal totalMoneyEarned;
static double totalScore;
static int totalKills;
static int totalLosses;
保存為:
stateVariables.totalLosses = totalLosses;
stateVariables.totalKills = totalKills;
stateVariables.totalScore = totalScore;
stateVariables.totalMoneyEarned = totalMoneyEarned;
stateVariables.money = money;
stateVariables.roundsPlayed = roundsPlayed;
或者這對我來說是什么搞砸了?
我創建了一個名為 appstate 的類:
namespace rngGame
{
[Serializable()]
public class AppState
{
public int roundsPlayed { get; set; }
public decimal money { get; set; }
public decimal totalMoneyEarned { get; set; }
public double totalScore { get; set; }
public int totalKills { get; set; }
public int totalLosses { get; set; }
public bool owned01 { get; set; }
public bool owned02 { get; set; }
public bool owned03 { get; set; }
public bool owneds01 { get; set; }
public bool owneds02 { get; set; }
public bool owneds03 { get; set; }
public double healthPotionCount { get; set; }
public int equipedWeapon { get; set; }
public int equipedShield { get; set; }
public int playerLevel { get; set; }
public int playerExpEarned { get; set; }
保存并退出(這部分確實有效,它確實創建了檔案):
static void closeAndSave()
{
string folder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
folder = Path.Combine(folder, "RNGgameSaveFiles");
Directory.CreateDirectory(folder);
string dataFile = Path.Combine(folder, "RNGgameSaveFileV1");
using (Stream stateStream = File.Create(dataFile))
{
BinaryFormatter serializer = new BinaryFormatter();
serializer.Serialize(stateStream, stateVariables);
}
}
uj5u.com熱心網友回復:
您有一些將值放入 stateVariables 并對其進行序列化的代碼,但您也必須做相反的事情 - 即,從中讀取值并將您的靜態成員設定為這些值。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/371003.html
上一篇:如何在C#中將powershell腳本傳遞給WindowsPowerShell主機?
下一篇:如何讓二維陣列正確格式化?
