Chuyển đến nội dung chính
ToanLB
Quay lại

PlayerPrefs, JsonUtility, Newtonsoft.Json hay Binary: Lựa chọn giải pháp lưu trữ nào cho dự án Unity?

~14 phút đọc
PlayerPrefs, JsonUtility, Newtonsoft.Json hay Binary: Lựa chọn giải pháp lưu trữ nào cho dự án Unity?

Hồi mới bắt đầu làm game với Unity, mình từng có thói quen nhét tất cả mọi thứ vào PlayerPrefs. Từ điểm số màn chơi, âm lượng, cấp độ nhân vật, cho đến cả danh sách trang bị trong kho đồ. Cứ mỗi lần người chơi nhặt được một thanh kiếm hay qua màn, chỉ cần gõ một dòng PlayerPrefs.SetString() hay PlayerPrefs.SetInt() là xong ngay. Lúc làm prototype thấy tiện và nhanh đến kỳ lạ.

Thế nhưng khi trò chơi bước vào giai đoạn thử nghiệm diện rộng, những vấn đề bắt đầu phát sinh:

Lúc này, câu hỏi quen thuộc thường được đặt ra giữa các anh em trong team: “Nên dùng PlayerPrefs, JsonUtility, Newtonsoft.Json hay Binary Serializer?”.

Để trả lời câu hỏi này một cách thấu đáo, chúng ta phải tách bạch rõ ràng hai tầng trách nhiệm độc lập: Nơi lưu trữ dữ liệu (Storage Medium) và Định dạng tuần tự hóa dữ liệu (Serialization Format).


1. Tách bạch ranh giới: Lưu ở đâu vs Chuyển đổi thế nào?

Nhiều người thường nhầm lẫn khi so sánh PlayerPrefs với JsonUtility hay Binary Serializer. Thực tế, chúng không nằm cùng một tầng kiến trúc:

flowchart LR
    subgraph SerializationLayer["Tầng Định Dạng (Serialization Format)"]
        F1["JsonUtility<br/>C++ Native, Phẳng"]
        F2["Newtonsoft.Json<br/>Linh hoạt, Dictionary"]
        F3["Binary Format<br/>MessagePack, MemoryPack"]
    end

    subgraph StorageLayer["Tầng Vận Chuyển & Lưu Trữ (Storage Medium)"]
        S1["PlayerPrefs Key-Value<br/>Registry, Plist"]
        S2["Disk File I/O<br/>Application.persistentDataPath"]
        S3["Cloud Save API<br/>Backend Remote Storage"]
    end

    SerializationLayer -->|"Xuất chuỗi ký tự hoặc mảng byte"| StorageLayer

Chúng ta hoàn toàn có thể dùng Newtonsoft.Json để chuyển đổi cả một kho đồ thành chuỗi JSON rồi nhét chuỗi đó vào PlayerPrefs. Nhưng liệu làm như vậy có hợp lý trong một dự án thương mại dài hơi? Chúng ta hãy cùng mổ xẻ từng ứng cử viên.


2. Phân tích chuyên sâu 4 giải pháp lưu trữ

1. PlayerPrefs: Phù hợp cho cấu hình người dùng và cờ trạng thái nhỏ

PlayerPrefs chỉ hỗ trợ trực tiếp ba kiểu dữ liệu nguyên thủy: int, float, và string.

2. JsonUtility: Tốc độ Native C++ cực nhanh nhưng hạn chế tính năng

UnityEngine.JsonUtility được Unity phát triển trực tiếp bằng C++ native bên dưới engine.

3. Newtonsoft.Json: Sự linh hoạt tối đa cho dữ liệu phức tạp

Còn được biết đến với tên gọi Json.NET, hiện đã có package chính thức của Unity (com.unity.nuget.newtonsoft-json).

4. Binary Serializer: Nhỏ gọn, tốc độ cao nhưng cần phân biệt rõ ràng

Khi nhắc đến Binary, nhiều tài liệu cũ thường đưa ra ví dụ về BinaryFormatter. Tuy nhiên, đây là cạm bẫy cực kỳ nguy hiểm.


3. Kiến trúc hệ thống Save Game Atomic chống hỏng file

Một hệ thống lưu game chuẩn mực trong dự án thực tế không chỉ dừng lại ở việc chọn Serializer nào, mà còn phải bảo vệ dữ liệu người chơi trước các sự cố sập nguồn hoặc tắt ứng dụng đột ngột.

Kỹ thuật cốt lõi ở đây là Ghi tệp nguyên tử (Atomic File Writing) kết hợp mã băm kiểm tra tính toàn vẹn (Checksum):

flowchart LR
    subgraph MemoryState["RAM"]
        Data["Player Save Profile"]
    end

    subgraph AtomicProcess["Quy Trình Ghi Nguyên Tử (Atomic Write)"]
        Temp["1. Ghi ra file tạm<br/>save.dat.tmp"]
        Swap["2. Hoán đổi an toàn<br/>File.Replace / Move"]
        Final["3. File Save chính thức<br/>save.dat"]
    end

    Data --> Temp
    Temp --> Swap
    Swap --> Final
  1. Bước 1: Tuần tự hóa và tính Checksum: Chuyển đổi dữ liệu sang định dạng mong muốn (JSON hoặc Binary), sau đó tính toán mã băm SHA-256 để chống can thiệp file trái phép.
  2. Bước 2: Ghi vào file tạm thời (.tmp): Toàn bộ dữ liệu được ghi vào một file tạm thời (ví dụ: save.dat.tmp). Nếu máy bị mất điện hoặc game bị crash ở bước này, file save chính thức trước đó vẫn còn nguyên vẹn 100%.
  3. Bước 3: Hoán đổi file an toàn (Atomic Swap): Sau khi ghi và flush dữ liệu xuống đĩa thành công, sử dụng File.Replace hoặc File.Move để thay thế file tạm thành file save chính thức. Thao tác này được hệ điều hành xử lý ở cấp độ con trỏ file trong hệ thống tập tin, diễn ra gần như tức thì và không bị rủi ro ghi đè dở dang.

4. Code demo và Kiểm chứng kỹ thuật bằng Unit Test

Dưới đây là một kiến trúc Save System hoàn chỉnh: tách rời hợp đồng tuần tự hóa qua interface ISaveSerializer, triển khai cho cả JsonUtility và Newtonsoft.Json, cùng với cơ chế ghi file nguyên tử kèm mã băm SHA-256.

using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;
using System.Collections.Generic;
using UnityEngine;
using Newtonsoft.Json;
using NUnit.Framework;

// Dữ liệu profile người chơi mẫu
[Serializable]
public class PlayerSaveProfile
{
    public string PlayerId;
    public int Level;
    public int Gold;
    public Dictionary<string, int> Inventory = new Dictionary<string, int>();

    public PlayerSaveProfile() { }

    public PlayerSaveProfile(string playerId, int level, int gold)
    {
        PlayerId = playerId;
        Level = level;
        Gold = gold;
    }
}

// Wrapper hỗ trợ JsonUtility khi cần xử lý dữ liệu có danh sách phẳng
[Serializable]
public class SimpleGameSettings
{
    public float MasterVolume = 1.0f;
    public string LanguageCode = "vi";
    public bool HapticEnabled = true;
}

// Hợp đồng bộ tuần tự hóa độc lập
public interface ISaveSerializer
{
    byte[] Serialize<T>(T data);
    T Deserialize<T>(byte[] bytes);
}

// Triển khai Newtonsoft.Json hỗ trợ đầy đủ Dictionary
public class NewtonsoftSaveSerializer : ISaveSerializer
{
    public byte[] Serialize<T>(T data)
    {
        string json = JsonConvert.SerializeObject(data, Formatting.None);
        return Encoding.UTF8.GetBytes(json);
    }

    public T Deserialize<T>(byte[] bytes)
    {
        string json = Encoding.UTF8.GetString(bytes);
        return JsonConvert.DeserializeObject<T>(json);
    }
}

// Triển khai JsonUtility tối ưu tốc độ cho schema phẳng trong Unity Runtime
public class JsonUtilitySaveSerializer : ISaveSerializer
{
    public byte[] Serialize<T>(T data)
    {
        string json = JsonUtility.ToJson(data);
        return Encoding.UTF8.GetBytes(json);
    }

    public T Deserialize<T>(byte[] bytes)
    {
        string json = Encoding.UTF8.GetString(bytes);
        return JsonUtility.FromJson<T>(json);
    }
}

// Triển khai Binary Serializer siêu tốc sử dụng BinaryWriter/BinaryReader
public class BinaryPayloadSerializer : ISaveSerializer
{
    public byte[] Serialize<T>(T data)
    {
        if (data is PlayerSaveProfile profile)
        {
            using var ms = new MemoryStream();
            using var writer = new BinaryWriter(ms, Encoding.UTF8);
            writer.Write(profile.PlayerId ?? string.Empty);
            writer.Write(profile.Level);
            writer.Write(profile.Gold);
            writer.Write(profile.Inventory.Count);
            foreach (var kvp in profile.Inventory)
            {
                writer.Write(kvp.Key);
                writer.Write(kvp.Value);
            }
            return ms.ToArray();
        }
        throw new NotSupportedException($"Kiểu {typeof(T).Name} chưa đăng ký bộ đọc nhị phân.");
    }

    public T Deserialize<T>(byte[] bytes)
    {
        if (typeof(T) == typeof(PlayerSaveProfile))
        {
            using var ms = new MemoryStream(bytes);
            using var reader = new BinaryReader(ms, Encoding.UTF8);
            var profile = new PlayerSaveProfile
            {
                PlayerId = reader.ReadString(),
                Level = reader.ReadInt32(),
                Gold = reader.ReadInt32()
            };
            int count = reader.ReadInt32();
            for (int i = 0; i < count; i++)
            {
                string key = reader.ReadString();
                int val = reader.ReadInt32();
                profile.Inventory[key] = val;
            }
            return (T)(object)profile;
        }
        throw new NotSupportedException($"Kiểu {typeof(T).Name} chưa đăng ký bộ đọc nhị phân.");
    }
}

// Trình quản lý lưu file nguyên tử (Atomic Save File Manager)
public class AtomicSaveFileManager
{
    private readonly ISaveSerializer _serializer;

    public AtomicSaveFileManager(ISaveSerializer serializer)
    {
        _serializer = serializer ?? throw new ArgumentNullException(nameof(serializer));
    }

    public void SaveAtomic<T>(string filePath, T data)
    {
        byte[] payload = _serializer.Serialize(data);
        string tempPath = filePath + ".tmp";
        string backupPath = filePath + ".bak";

        // 1. Ghi ra file tạm thời
        File.WriteAllBytes(tempPath, payload);

        // 2. Hoán đổi an toàn sang file chính thức
        if (File.Exists(filePath))
        {
            File.Replace(tempPath, filePath, backupPath);
            if (File.Exists(backupPath))
            {
                File.Delete(backupPath);
            }
        }
        else
        {
            File.Move(tempPath, filePath);
        }
    }

    public T Load<T>(string filePath)
    {
        if (!File.Exists(filePath))
        {
            throw new FileNotFoundException($"Save file not found at: {filePath}");
        }

        byte[] bytes = File.ReadAllBytes(filePath);
        return _serializer.Deserialize<T>(bytes);
    }

    public static string ComputeSha256Checksum(byte[] data)
    {
        using var sha256 = SHA256.Create();
        byte[] hash = sha256.ComputeHash(data);
        return BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant();
    }
}

[TestFixture]
public class SaveSystemArchitectureTests
{
    private string _testDirectory;

    [SetUp]
    public void SetUp()
    {
        _testDirectory = Path.Combine(Path.GetTempPath(), "SaveSystemTests_" + Guid.NewGuid().ToString("N"));
        Directory.CreateDirectory(_testDirectory);
    }

    [TearDown]
    public void TearDown()
    {
        if (Directory.Exists(_testDirectory))
        {
            Directory.Delete(_testDirectory, true);
        }
    }

    [Test]
    public void NewtonsoftSerializer_RoundTrip_PreservesDictionaryData()
    {
        var serializer = new NewtonsoftSaveSerializer();
        var profile = new PlayerSaveProfile("player_hero_01", 15, 5000);
        profile.Inventory["sword_flame"] = 1;
        profile.Inventory["potion_mana"] = 20;

        byte[] serializedBytes = serializer.Serialize(profile);
        PlayerSaveProfile loadedProfile = serializer.Deserialize<PlayerSaveProfile>(serializedBytes);

        Assert.IsNotNull(loadedProfile);
        Assert.AreEqual("player_hero_01", loadedProfile.PlayerId);
        Assert.AreEqual(15, loadedProfile.Level);
        Assert.AreEqual(5000, loadedProfile.Gold);
        Assert.AreEqual(2, loadedProfile.Inventory.Count);
        Assert.AreEqual(20, loadedProfile.Inventory["potion_mana"]);
    }

    [Test]
    public void BinarySerializer_RoundTrip_PacksCompactPayload()
    {
        var serializer = new BinaryPayloadSerializer();
        var profile = new PlayerSaveProfile("archer_77", 25, 1250);
        profile.Inventory["arrow_fire"] = 100;

        byte[] binaryBytes = serializer.Serialize(profile);
        PlayerSaveProfile loadedProfile = serializer.Deserialize<PlayerSaveProfile>(binaryBytes);

        Assert.IsNotNull(loadedProfile);
        Assert.AreEqual("archer_77", loadedProfile.PlayerId);
        Assert.AreEqual(25, loadedProfile.Level);
        Assert.AreEqual(1250, loadedProfile.Gold);
        Assert.AreEqual(100, loadedProfile.Inventory["arrow_fire"]);
        // Dung lượng binary gọn gàng, nhỏ hơn JSON thông thường
        Assert.Less(binaryBytes.Length, 100);
    }

    [Test]
    public void AtomicSaveFileManager_SaveAndLoad_WritesAndReadsCorrectly()
    {
        var serializer = new NewtonsoftSaveSerializer();
        var manager = new AtomicSaveFileManager(serializer);
        string savePath = Path.Combine(_testDirectory, "slot_1.dat");

        var profile = new PlayerSaveProfile("knight_99", 50, 100000);
        profile.Inventory["shield_aegis"] = 1;

        // Lưu dữ liệu nguyên tử
        manager.SaveAtomic(savePath, profile);

        Assert.IsTrue(File.Exists(savePath));
        Assert.IsFalse(File.Exists(savePath + ".tmp"));

        // Nạp lại và kiểm tra
        PlayerSaveProfile loadedProfile = manager.Load<PlayerSaveProfile>(savePath);
        Assert.AreEqual("knight_99", loadedProfile.PlayerId);
        Assert.AreEqual(50, loadedProfile.Level);
        Assert.AreEqual(1, loadedProfile.Inventory["shield_aegis"]);
    }

    [Test]
    public void ChecksumValidation_DetectsPayloadTampering()
    {
        byte[] originalData = Encoding.UTF8.GetBytes("PlayerGold:1000;Gem:50");
        string originalChecksum = AtomicSaveFileManager.ComputeSha256Checksum(originalData);

        // Giả lập người chơi can thiệp sửa file tăng vàng lên 9999
        byte[] tamperedData = Encoding.UTF8.GetBytes("PlayerGold:9999;Gem:50");
        string tamperedChecksum = AtomicSaveFileManager.ComputeSha256Checksum(tamperedData);

        Assert.AreNotEqual(originalChecksum, tamperedChecksum);
    }
}

5. Bảng so sánh Trade-off giữa các giải pháp lưu trữ

Dưới đây là ma trận đối chiếu toàn diện giúp anh em đưa ra quyết định kiến trúc chính xác:

Tiêu chíPlayerPrefsJsonUtilityNewtonsoft.JsonBinary (MessagePack/Protobuf)
Bản chất cốt lõiKey-Value Store nền tảngBộ tuần tự hóa JSON C++ NativeBộ tuần tự hóa JSON C# BCLBộ tuần tự hóa nhị phân hiện đại
Hỗ trợ DictionaryKhôngKhôngCó (Đầy đủ mọi loại Key)Có (Tối ưu hóa bảng băm)
Tốc độ thực thiNhanh với biến nhỏ lẻCực nhanh (Native C++)Trung bình (Reflection)Siêu tốc (AOT Byte Stream)
Cấp phát Heap (GC)Không đáng kểRất thấp (FromJsonOverwrite)Đáng kể (Tạo chuỗi và DTO)Cực thấp (Zero/Low Allocation)
Khả năng đọc/DebugKhó (Nằm trong Registry)Dễ (Đọc trực tiếp file JSON)Dễ (Format đẹp, dễ sửa lỗi)Khó (Cần tool chuyển sang JSON)
Độ an toàn dữ liệuKém (Dễ can thiệp Registry)Cần thêm lớp mã hóa AESCần thêm lớp mã hóa AESKhó chỉnh sửa tay bằng text editor
Trường hợp lý tưởngCấu hình UI, âm lượng, cờDữ liệu phẳng, cần nạp nhanhDữ liệu RPG sâu, Save game chínhGame nhiều data, nhiều lượt save/load

6. Chiến lược thực tế khi lựa chọn giải pháp lưu trữ

Trong một dự án game quy mô thương mại, chúng ta không nhất thiết phải chọn một giải pháp duy nhất cho toàn bộ hệ thống. Mô hình phối hợp thực tế thường bao gồm:

  1. Sử dụng PlayerPrefs cho cài đặt thiết bị (Local Device Preferences): Chỉ dùng để lưu các tùy chọn không ảnh hưởng tới tiến trình gameplay: âm lượng, độ sáng màn hình, bật tắt rung, ngôn ngữ, định danh tài khoản đăng nhập lần cuối.
  2. Sử dụng JsonUtility cho các bảng cấu hình tĩnh: Nếu chúng ta nạp hàng nghìn dòng dữ liệu nhiệm vụ hoặc chỉ số quái vật từ file JSON đóng gói sẵn trong streaming assets, JsonUtility là lựa chọn tuyệt vời nhờ tốc độ native C++ và cơ chế ghi đè bộ nhớ hạn chế rác.
  3. Sử dụng Newtonsoft.Json cho Save Game người chơi trong giai đoạn Production: Khi game đang trong quá trình phát triển tính năng, dữ liệu thay đổi liên tục, việc dùng file JSON giúp lập trình viên và Game Designer dễ dàng mở file kiểm tra, sửa trực tiếp state để tái hiện bug.
  4. Chuyển sang Binary (MessagePack/Protobuf) khi tối ưu Release: Khi cấu trúc dữ liệu đã ổn định và game có nhu cầu tối ưu dung lượng tải về, tốc độ nạp màn chơi (Loading Time) và giảm thiểu tình trạng người chơi can thiệp file save thô, hãy nâng cấp lên MessagePack thông qua việc thay thế interface ISaveSerializer mà không cần sửa đổi gameplay logic.

7. Lời kết

PlayerPrefs giải quyết bài toán nơi lưu trữ cấu hình đơn giản. Còn JsonUtility, Newtonsoft.Json và Binary Serializer giải quyết bài toán chuyển hóa cấu trúc object trong bộ nhớ.

Không có giải pháp nào vượt trội trong mọi hoàn cảnh. Một kiến trúc Save System bền vững là kiến trúc biết bóc tách rõ ràng giữa định dạng dữ liệu và thao tác I/O xuống đĩa, đồng thời trang bị đầy đủ cơ chế ghi file nguyên tử và kiểm tra checksum để bảo vệ an toàn tuyệt đối cho tiến trình chơi của game thủ.


Chia sẻ bài viết:
Lương Bảo Toàn

Lương Bảo Toàn

Mình làm ở mảng HMI Automotive và Game, mình chia sẻ những kiến thức, kinh nghiệm, những câu chuyện mình cho là hay ho trong quá trình làm nghề.

Bài viết này có mang lại giá trị cho bạn?

Nếu bài viết giúp ích cho công việc của bạn, hay đơn giản thấy nó hay hoặc muốn ủng hộ mình bạn có thể

Mời mình ly cafe

Bài viết cùng chủ đề

Bình luận & Thảo luận

Powered by Giscus

Nhận bài viết mới qua Email

Đăng ký để không bỏ lỡ những bài viết mới từ mình nhé.

* Không spam. Bạn có thể huỷ đăng ký bất kỳ lúc nào chỉ với 1 click.