You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Unity游戏数据保存失败求助:序列化存储整数功能异常排查

游戏保存功能问题排查与修复方案

嘿,我帮你梳理下代码里的几个核心问题,一个个解决就能让保存功能正常工作啦:

1. Save类没法响应Update方法

你给Save类加了[System.Serializable],但它没有继承MonoBehaviour,Unity根本不会调用里面的Update方法,所以你按T/Y键完全没反应。得把逻辑拆成两部分:一个纯序列化的数据类,一个挂载在GameObject上的管理脚本负责处理输入和保存加载。

2. 序列化类不匹配+拼写错误

你在SaveGame里写了Game save = new Game(Cuens);,但代码里根本没定义Game类,明显是笔误,应该用你定义的序列化类(我改成了SaveData,名字更清晰)。另外LodeGame拼错啦,应该是LoadGame,不然方法调用都会出问题。

3. 缺失必要的命名空间

代码里用到了BinaryFormatterFileStream这些类,得在顶部加对应的命名空间,不然编译都会报错。

修复后的完整代码

using UnityEngine;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

// 纯数据类,负责存要保存的数值,标记可序列化
[System.Serializable] 
public class SaveData { 
    public int Cuens; 
}

// 挂载在场景物体上的管理脚本,处理输入和保存加载逻辑
public class SaveLoadManager : MonoBehaviour { 
    void Update () { 
        // 用GetKeyDown避免按住键连续触发,按一次T只加一次数值
        if (Input.GetKeyDown(KeyCode.T)) { 
            SaveData currentData = new SaveData();
            currentData.Cuens += 5;
            SaveGame(currentData);
            Debug.Log($"当前数值:{currentData.Cuens},已保存到本地");
        }
        
        // 按Y加载存档
        if (Input.GetKeyDown(KeyCode.Y)) { 
            SaveData loadedData = LoadGame();
            if (loadedData != null) {
                Debug.Log($"加载成功!存档数值:{loadedData.Cuens}");
            }
        }
    } 

    void SaveGame(SaveData data) { 
        BinaryFormatter bf = new BinaryFormatter(); 
        // 用Path.Combine更安全,避免路径拼接出错
        string savePath = Path.Combine(Application.persistentDataPath, "gamesave.save");
        FileStream file = File.Create(savePath); 
        bf.Serialize(file, data); 
        file.Close(); 
    } 

    SaveData LoadGame() { 
        string savePath = Path.Combine(Application.persistentDataPath, "gamesave.save");
        // 先检查存档文件是否存在,避免加载时报错
        if (!File.Exists(savePath)) {
            Debug.LogWarning("找不到存档文件哦");
            return null;
        }

        BinaryFormatter bf = new BinaryFormatter(); 
        FileStream file = File.Open(savePath, FileMode.Open); 
        SaveData loadedData = (SaveData)bf.Deserialize(file); 
        file.Close(); 
        return loadedData;
    } 
}

最后要做的小事

SaveLoadManager脚本挂载到场景里的任意一个GameObject上(比如新建个空物体叫SaveManager),运行游戏后按T键就能增加数值并保存,按Y键就能加载存档啦。

内容的提问来源于stack exchange,提问作者dym111

火山引擎 最新活动