简体   繁体   English

Unity - 如何保存和加载列表(二进制保存和加载)

[英]Unity - How to save and load lists (Binary Saving and Loading)

I'm trying to figure out how you would save & load list of data.我试图弄清楚你将如何保存和加载数据列表。 I've gotten my code to work with single data but unsure of how a list one would work.我已经让我的代码可以处理单个数据,但不确定列表如何工作。 I have a Character class so that means I can have multiple characters and I would like to save each of those character's hp, mana etc.我有一个角色 class 这意味着我可以有多个角色,我想保存每个角色的 hp、mana 等。

//SaveManager class that I can call from anywhere to save and load
public static class SaveManager 
{
    //SAVE
    public static void Save(Character c)
    {
        BinaryFormatter formatter = new BinaryFormatter();
        string path = Application.persistentDataPath + "/Save.save";
        FileStream stream = new FileStream(path, FileMode.Create);

        PartyData data = new PartyData(c);

        formatter.Serialize(stream, data);
        stream.Close();
    }

    //LOAD
    public static PartyData Load()
    {
        string path = Application.persistentDataPath + "/Save.save";
        if (File.Exists(path))
        {
            BinaryFormatter formatter = new BinaryFormatter();
            FileStream stream = new FileStream(path, FileMode.Open);

            PartyData data = formatter.Deserialize(stream) as PartyData;
            stream.Close();

            return data;
        }
        else
        {
            Debug.Log("Save FIle not Found");
            return null;
        }
    }

}

PartyData class is what I'm using to save the Character data to. PartyData class 是我用来保存字符数据的。

[System.Serializable]
public class PartyData
{
    public int hp;

    public PartyData(Character cParty)
    {
        hp = cParty.HP;       
    }
}

Character class that contains stats etc包含统计信息等的字符 class

public class Character
{
   public int HP { get; set; }

   public int Mana { get; set; }
}

And then finally I have the CharacterParty class that I attach to a gameobject, this class contains multiple characters and calls the Save and Load functions:最后,我有附加到游戏对象的 CharacterParty class,这个 class 包含多个字符并调用保存和加载函数:

public class CharacterParty : MonoBehaviour
{
    [SerializeField] List<Character> characters;

    public List<Character> Characters
    {
        get
        {
            return characters;
        }
    }

    public void SaveParty()
    {
        SaveManager.SaveMC(characters[0]);
    }
    public void LoadParty()
    {
        PartyData data = SaveManager.LoadMC();

        characters[0].HP = data.hp;

    }
}

Now for testing purposes I tried saving & loading just the character's hp at index 0 and it works but now I wanna save a list of multiple character's hp and mana etc. I just don't know how the list would work with serialization saving and loading.现在出于测试目的,我尝试仅在索引 0 处保存和加载角色的 hp,它可以工作,但现在我想保存多个角色的 hp 和法力等列表。我只是不知道该列表如何与序列化保存和加载一起使用. My code probably needs a little bit of change to get the list working so I hope someone can help me out with an example.我的代码可能需要一些更改才能使列表正常工作,所以我希望有人可以帮助我举个例子。

Use JsonUtility class - this is Unity's built-in utility for JSON.使用JsonUtility class - 这是 Unity 用于 JSON 的内置实用程序。

Also with this you can serialize any class without [System.Serializable]此外,您可以在没有 [System.Serializable] 的情况下序列化任何 class

Save:节省:

// Parties list
List<PartyData> parties = new List<PartyData>();

// Add your parties here
// First argument is an instance of a class or any other object
// If second argument set to true, it makes JSON more human-readable
string json = JsonUtility.ToJson(parties, false);

// .. saving the file

Load:加载:

// .. loading the file

// First argument is the JSON
List<PartyData> parties = JsonUtility.FromJson<List<PartyData>>(json);

// .. do stuff with the list

EDIT:编辑:

If you really want to use BinaryFormatter, then this is for saving:如果你真的想使用 BinaryFormatter,那么这是为了保存:

List<PartyData> parties = new List<PartyData>();
// .. add parties
formatter.Serialize(stream, parties)

For loading:加载:

List<PartyData> parties = formatter.Deserialize(stream) as List<PartyData>;
// .. do stuff

SECOND EDIT:第二次编辑:

This one should work.这个应该可以的。 You would do something like that:你会做这样的事情:

// Save class
[Serializable]
public class Save
{
    public List<PartyData> parties;
    // .. add other stuff here
}

// For loading
try
{
    // Deserializing the save
    Save save = (Save)formatter.Deserialize(stream);
    // .. do stuff with other data if you added some
    foreach (PartyData data in save.parties)
    {
        // .. do stuff with data
    }
}
catch (Exception e)
{
    // .. can you just acnowledge... E
    // Oopsie! An error occured. The save file is probably COWWUPTED
    Debug.LogWarning($"An error occured while loading the file: {e}");
}

// For saving
List<PartyData> parties = new List<PartyData>();
// .. add parties by calling parties.Add(party_here);
// Creating a save
Save save = new Save();
// Adding parties to save
save.parties = parties;
// Serialize to a file
formatter.Serialize(stream, parties);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM