如何加载保存在Unity C#中的对象数据?

时间:2019-02-21 17:01:35

标签: unity3d

我想在Unity C#中创建一个通用存储系统。 我的代码不起作用?对象无法定义或我写错了吗?

如果不使用SaveExtensions中的功能,则一切正常。

https://drive.google.com/open?id=1hLFRB2rHj7XcJT6et7TskEa7sLwdmJhP

1 个答案:

答案 0 :(得分:0)

在保存时,问题出在您的Load方法中。

obj = bf.Deserialize(fs);

此更改仅在方法内部本地应用,但实际上并未更改调用中的ex的值

ex.Load("asd", ".dat", SaveExtension.Path.PersistentDataPath);

不幸的是,扩展方法中不允许使用refout,因此一种解决方法是改为给该方法一个适当的返回值(我还对其余代码进行了一些更改):

[System.Serializable]
internal static class SaveExtension
{
    public enum Path 
    { 
        PersistentDataPath, 
        TemporaryCachePath 
    }

    public static void Save(this object obj, string name, string type, Path path)
    {
        var pathString = "";

        switch (path)
        {
            case Path.PersistentDataPath:
                pathString = Application.persistentDataPath;
                break;
            case Path.TemporaryCachePath:
                pathString = Application.temporaryCachePath;
                break;
        }

        // There is no need to create the file 
        // in a dedicated if block since it will be created anyway
        // Additionally: You did only create a new file but due to
        // if-else you didn't write to it the first time

        Debug.Log("[SaveSystem]: File " + name + type + " already exist!");
        Debug.Log("[SaveSystem]: Location: " + pathString + "/" + name + type);

        var bf = new BinaryFormatter();
        using (var fs = File.Open(pathString + "/" + name + type, FileMode.Open, FileAccess.Write))
        {
            bf.Serialize(fs, obj);
        }

        Debug.Log("[SaveSystem]: Object succesful serialized!");
    }

    public static T Load<T>(this T obj, string name, string type, Path path)
    {
        var output = default(T);

        var pathString = "";

        switch (path)
        {
            case Path.PersistentDataPath:
                pathString = Application.persistentDataPath;
                break;
            case Path.TemporaryCachePath:
                pathString = Application.temporaryCachePath;
                break;
        }

        if (!File.Exists(pathString + "/" + name + type))
        {
            Debug.LogFormat("File " + pathString + "/" + name + type + " not found! returning default value.");
            return output;
        }

        var bf = new BinaryFormatter();
        using (var fs = File.Open(pathString + "/" + name + type, FileMode.Open))
        {
            output = (T)bf.Deserialize(fs);
        }

        Debug.Log("[SaveSystem]: Object succesful deserialized!");

        return output;
    }
}

并像使用它

ex = ex.Load("asd", ".dat", SaveExtension.Path.PersistentDataPath);

通过这种方式,this T obj仅用于定义类型T


只是一个提示:切勿使用Debug.Log内的Update ...进行调试,只需将Unity中的Inspector切换到Debug mode,就可以直接看到私有字段。