U
章 05导出到手机7 课 — 点击打开
04 / 07 · 10 分钟
导出到手机

保存进度

到目前为止的项目

Assets/

Scenes/

Arena.unity

Knight

Scripts/

CharacterStats.csEquipment.csSaveData.csSaveSystem.csGameSession.cs

你已经有的这一课新增

手游会不停地被打断:来电话、来通知,系统还会为了腾内存直接把应用杀掉。如果一关应用就丢进度,没有人会再回来玩。

动态图解

把一个普通的 C# 类转成 JSON,写进 persistentDataPath,下次启动时再读回来。

用 PlayerPrefs 还是用文件?

✓ PlayerPrefs

只有三种类型(int、float、string),没有结构,存在 registry 或 plist 文件里。放音量滑块和 Invert Y 很合适,放游戏状态就非常糟。

✓ JSON file

整棵对象树放进一个文件,能打开查看、能备份、能标 version。这才是真正意义上的存档文件。

第 1 步 —— 一个纯数据 class

存档类里只放值,不放 MonoBehaviour。GameObject 没法被 serialise,所以改成把重建它所需的信息记下来。

SaveData.cs
using System;
using System.Collections.Generic;
using UnityEngine;

[Serializable]
public class SaveData
{
    public int version = 1;              // bump this when the shape changes

    public int level = 1;
    public float health = 100f;
    public int gold;
    public float playTimeSeconds;

    public string sceneName = "Arena";
    public Vector3 playerPosition;       // Unity serialises Vector3 fine

    public List<string> ownedArtifacts = new List<string>();
    public List<string> equippedArtifacts = new List<string>();

    public string savedAtUtc = "";
}

第 2 步 —— 写入和读取

SaveSystem.cs
using System;
using System.IO;
using UnityEngine;

public static class SaveSystem
{
    // the ONLY folder you are allowed to write to on iOS and Android
    private static string Path => System.IO.Path.Combine(Application.persistentDataPath, "save.json");

    public static bool Exists => File.Exists(Path);

    public static void Save(SaveData data)
    {
        data.savedAtUtc = DateTime.UtcNow.ToString("o");

        string json = JsonUtility.ToJson(data, prettyPrint: true);
        string temp = Path + ".tmp";

        // if the phone dies mid-write, the old save is still intact
        File.WriteAllText(temp, json);
        File.Copy(temp, Path, overwrite: true);
        File.Delete(temp);

        Debug.Log("Saved to " + Path);
    }

    public static SaveData Load()
    {
        if (!Exists) return new SaveData();          // first run

        try
        {
            string json = File.ReadAllText(Path);
            SaveData data = JsonUtility.FromJson<SaveData>(json);
            return Migrate(data);
        }
        catch (Exception e)
        {
            // a corrupt save must never brick the game
            Debug.LogError("Save file unreadable, starting fresh: " + e.Message);
            File.Move(Path, Path + ".broken");
            return new SaveData();
        }
    }

    public static void Delete()
    {
        if (Exists) File.Delete(Path);
    }

    /// old saves must keep working after you ship an update
    private static SaveData Migrate(SaveData data)
    {
        if (data.version < 1)
        {
            data.gold = 0;
            data.version = 1;
        }
        return data;
    }
}
  • Application.persistentDataPath 是手机上唯一能写的目录。Application.dataPath 在应用包里面,只能读。

  • 先写临时文件再交换,是为了防止写到一半被系统杀掉,留下一个写坏的存档。

  • Load 一定要用 try/catch 包住。文件坏了打不开游戏的玩家,只会留下一个一星评价。

  • version 字段现在几乎不花什么成本,等你在 1.3 版本加新字段那天,它会救你一命。

第 3 步 —— 在正确的时机保存

别每帧都存,但也别只在玩家点按钮的时候才存 —— 在手机上,他们根本来不及点。

GameSession.cs
using UnityEngine;

public class GameSession : MonoBehaviour
{
    public static GameSession Instance { get; private set; }
    public SaveData Data { get; private set; }

    [SerializeField] private CharacterStats playerStats;   // the Knight's
    [SerializeField] private Transform player;

    void Awake()
    {
        if (Instance != null) { Destroy(gameObject); return; }
        Instance = this;
        DontDestroyOnLoad(gameObject);

        Data = SaveSystem.Load();
        Apply(Data);
    }

    void Update() => Data.playTimeSeconds += Time.deltaTime;

    void Collect()
    {
        Data.health = playerStats.currentHealth;
        Data.playerPosition = player.position;
        Data.sceneName = UnityEngine.SceneManagement.SceneManager.GetActiveScene().name;
    }

    void Apply(SaveData d)
    {
        playerStats.currentHealth = d.health;
        if (d.playerPosition != Vector3.zero) player.position = d.playerPosition;
    }

    /// fires when the app goes to the background — THIS is the important one on mobile
    void OnApplicationPause(bool paused)
    {
        if (paused) { Collect(); SaveSystem.Save(Data); }
    }

    /// desktop and a graceful exit
    void OnApplicationQuit()
    {
        Collect();
        SaveSystem.Save(Data);
    }
}

靠检查点存档,别把自动保存刷屏

  • 玩家进入新区域、打完一场战斗、买了东西,或者应用被切到后台时,就存一次。

  • 写一个小 JSON 文件大概一毫秒,但一秒写 60 次照样会把闪存磨坏。

  • 存完闪一下“已保存”的小提示,半秒就够。玩家不信任那些看不见存档动作的游戏。

找到那个文件来调试

terminal
# print the path from inside the game
Debug.Log(Application.persistentDataPath);

# Android — pull the save off the device
adb shell run-as com.yourstudio.yourgame cat files/save.json

# Editor paths
# macOS   ~/Library/Application Support/CompanyName/ProductName/
# Windows %USERPROFILE%\AppData\LocalLow\CompanyName\ProductName\