UnityDatabase 1.0.0

dotnet add package UnityDatabase --version 1.0.0
                    
NuGet\Install-Package UnityDatabase -Version 1.0.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="UnityDatabase" Version="1.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="UnityDatabase" Version="1.0.0" />
                    
Directory.Packages.props
<PackageReference Include="UnityDatabase" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add UnityDatabase --version 1.0.0
                    
#r "nuget: UnityDatabase, 1.0.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package UnityDatabase@1.0.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=UnityDatabase&version=1.0.0
                    
Install as a Cake Addin
#tool nuget:?package=UnityDatabase&version=1.0.0
                    
Install as a Cake Tool

UnityDatabase

Thư viện UnityDatabase là giải pháp lưu trữ dữ liệu dạng snapshot cho các tựa game/ứng dụng Unity, sử dụng MySQL làm hệ quản trị cơ sở dữ liệu và Google Protobuf để tuần tự hóa (serialization) dữ liệu.

Điểm nổi bật lớn nhất của thư viện là khả năng hoạt động bất đồng bộ hoàn toàn (Non-blocking) trên luồng chính (Main Thread) của Unity. Mọi tác vụ nặng như serialize/deserialize và thao tác I/O với cơ sở dữ liệu đều được chạy ẩn trên các Background Thread, giúp game luôn giữ được FPS ổn định và mượt mà, đồng thời an toàn khi gọi các Unity API nhờ vào cơ chế callback thông qua Tick().

Tính Năng Chính

  • Tự động khởi tạo DB & Bảng: Chỉ cần truyền thông tin kết nối, hệ thống sẽ tự động khởi tạo Database và bảng (table) nếu chưa tồn tại.
  • Background Serialization: Quá trình chuyển đổi dữ liệu (IMessagebyte[]) được thực hiện trên luồng chạy ngầm.
  • Batch Write Tối Ưu: Gom hàng loạt thao tác lưu dữ liệu (Save) và ghi xuống cơ sở dữ liệu MySQL thông qua 1 Transaction duy nhất, giúp tốc độ ghi tăng lên gấp hàng chục lần so với ghi từng bản ghi lẻ.
  • Main Thread Callback: Cơ chế trả kết quả qua delegate/callback an toàn. Bạn chỉ cần gọi Tick() trong Update() của Unity để nhận callback trên Main Thread.
  • Độc Lập & Nhẹ Nhàng: Sử dụng netstandard2.0, tương thích ngược tốt, phù hợp cho hầu hết các phiên bản Unity (2020+).

Yêu cầu hệ thống

  • Unity: 2020.3 hoặc mới hơn.
  • C#: Ngôn ngữ C# 9.0 (.NET Standard 2.0).
  • Database: Một máy chủ MySQL (Local hoặc Remote).

Thư viện phụ thuộc (Dependencies):

  • MySqlConnector (Phiên bản >= 2.3.7)
  • Google.Protobuf (Phiên bản >= 3.25.3)

Cài đặt

  1. Tải source code hoặc build ra thư viện liên kết động (.dll) qua câu lệnh:
    dotnet build -c Release
    
  2. Copy các file .dll vào thư mục Assets/Plugins của project Unity.
  3. Nếu bạn sử dụng NuGet cho Unity, bạn có thể đóng gói (.nupkg) và import trực tiếp.

Hướng dẫn sử dụng

1. Khởi tạo Database

Tạo một thể hiện của SnapshotDB và kết nối với máy chủ MySQL. Việc này thường được thực hiện ở Awake() hoặc Start() của một Manager script.

using UnityDatabase.Core;
using UnityDatabase.Configuration;

public class DatabaseManager : MonoBehaviour
{
    private SnapshotDB _db;

    void Start()
    {
        var config = new SnapshotDBConfig 
        {
            MaxBatchSize = 500, // Số lượng tối đa bản ghi gom chung 1 lần ghi
            FlushInterval = TimeSpan.FromMilliseconds(100), // Thời gian đợi tối đa gom batch
            MaxPoolSize = 10 
        };

        _db = new SnapshotDB(
            host: "localhost",
            port: 3306,
            databaseName: "game_database",
            username: "root",
            password: "your_password",
            config: config
        );

        // Đăng ký bắt lỗi background (nếu cần)
        _db.OnError += ex => Debug.LogError($"Database Error: {ex}");
    }

    void OnDestroy()
    {
        _db?.Dispose(); // Rất quan trọng, phải gọi khi thoát game để giải phóng bộ nhớ
    }
}

2. Gọi Tick() mỗi frame

Để đảm bảo các callback (sau khi Load) được gọi an toàn trên Main Thread (cho phép sử dụng các API của Unity như Instantiate, GetComponent...), bạn bắt buộc phải gọi hàm Tick() mỗi frame.

void Update()
{
    _db?.Tick();
}

3. Lưu dữ liệu (Save)

Hàm Save hoạt động theo dạng fire-and-forget. Luồng chính chỉ lưu trữ địa chỉ tham chiếu (reference) của IMessage, còn việc Serialize và Ghi DB sẽ diễn ra trên một Thread riêng biệt.

Data Class (ví dụ khai báo bằng Protobuf):

message PlayerData {
    string Name = 1;
    int32 Level = 2;
    int32 Hp = 3;
}

Sử dụng C#:

var player = new PlayerData { Name = "Hero", Level = 10, Hp = 100 };

// Cú pháp: Save(loại_dữ_liệu, định_danh_duy_nhất, dữ_liệu_protobuf)
_db.Save("player", "player_001", player);

// Lưu xong, game cứ tiếp tục chạy mà không bị khựng (block).

4. Đọc dữ liệu (Load)

Bạn có thể đọc một bản ghi cụ thể hoặc đọc tất cả bản ghi thuộc về một type nào đó.

// Đọc 1 bản ghi
_db.Load<PlayerData>("player", "player_001", data => 
{
    // Đoạn code trong này ĐƯỢC CHẠY TRÊN MAIN THREAD (nhờ hàm Tick())
    if (data != null)
    {
        Debug.Log($"Loaded: {data.Name} (Level {data.Level})");
        // Update UI an toàn:
        // hpText.text = data.Hp.ToString();
    }
});

// Đọc tất cả bản ghi của một type
_db.LoadAll<PlayerData>("player", entries => 
{
    foreach(var entry in entries)
    {
        Debug.Log($"Key: {entry.Key}, Name: {entry.Data.Name}");
    }
});

5. Xóa dữ liệu (Delete)

Việc xóa cũng diễn ra trên background thread.

_db.Delete("player", "player_001");

6. Đẩy dữ liệu bắt buộc (Flush)

Khi bạn muốn tắt game hoặc cần chắc chắn rằng tất cả những dữ liệu bạn vừa gọi Save() (đang nằm trong hàng đợi) được ghi ngay lập tức xuống đĩa cứng (MySQL), hãy gọi Flush(). Lưu ý: Gọi Flush() sẽ block (chặn) luồng gọi cho đến khi quá trình ghi hoàn tất.

_db.Flush();

Kiến trúc Threading

Nhằm tối đa hóa hiệu năng cho Unity, thư viện được cấu trúc như sau:

Thao tác Luồng Chính (Unity Main Thread) Luồng Chạy Ngầm (Background Thread)
Lưu (Save) Đẩy tham chiếu IMessage vào hàng đợi. Lấy tham chiếu ra → Chuyển thành byte[] (Serialize) → Ghi vào MySQL qua Batch.
Đọc (Load) Yêu cầu đọc dữ liệu. Đọc byte[] từ MySQL → Deserialize sang IMessage → Đẩy Callback vào hàng đợi.
Nhịp (Tick) Chạy các Callback từ hàng đợi (An toàn gọi Unity API).

Đóng góp

Nếu có lỗi phát sinh hoặc ý tưởng cải thiện, bạn vui lòng mở Pull Request hoặc Issue.

License

MIT License

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.0 59 4/28/2026