Unity中5种数据保存方式

PlayerPrefs(适用于小型数据存储)

适用于存储简单的键值对(如设置、分数等)。数据会存储在注册表(Windows)或Library/Preferences(macOS)等系统目录中。

// 保存数据
PlayerPrefs.SetInt("HighScore", 100);
PlayerPrefs.SetFloat("Volume", 0.8f);
PlayerPrefs.SetString("PlayerName", "Alice");
PlayerPrefs.Save();  // 立即保存数据

// 读取数据
int highScore = PlayerPrefs.GetInt("HighScore", 0);
float volume = PlayerPrefs.GetFloat("Volume", 1.0f);
string playerName = PlayerPrefs.GetString("PlayerName", "DefaultName");


优点:简单易用,无需额外文件操作

缺点:只能存储intfloatstring,容量有限,数据容易被篡改

2.使用System.IO将数据保存到 JSON文件中(适用于存储对象数据,易读易写)
using System.IO;
using UnityEngine;

[System.Serializable]
public class PlayerData {
    public int level;
    public float health;
    public string playerName;
}

// 保存数据到 JSON
public static void SaveData(PlayerData data) {
    string json = JsonUtility.ToJson(data, true);
    File.WriteAllText(Application.persistentDataPath + "/playerData.json", json);
}

// 读取数据
public static PlayerData LoadData() {
    string path = Application.persistentDataPath + "/playerData.json";
    if (File.Exists(path)) {
        string json = File.ReadAllText(path);
        return JsonUtility.FromJson<PlayerData>(json);
    }
    return new PlayerData(); // 默认数据
}



优点

  • 适用于存储复杂数据
  • JSON 格式易读

缺点

  • 没有加密,数据容易被修改
3.使用BinaryFormatter进行二进制存储
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using UnityEngine;

[System.Serializable]
public class PlayerData {
    public int level;
    public float health;
}

// 保存数据
public static void SaveBinary(PlayerData data) {
    BinaryFormatter formatter = new BinaryFormatter();
    using (FileStream stream = new FileStream(Application.persistentDataPath + "/playerData.dat", FileMode.Create)) {
        formatter.Serialize(stream, data);
    }
}

// 读取数据
public static PlayerData LoadBinary() {
    string path = Application.persistentDataPath + "/playerData.dat";
    if (File.Exists(path)) {
        BinaryFormatter formatter = new BinaryFormatter();
        using (FileStream stream = new FileStream(path, FileMode.Open)) {
            return (PlayerData)formatter.Deserialize(stream);
        }
    }
    return new PlayerData();
}

优点

  • 更紧凑,占用更少空间
  • 适用于复杂数据

缺点

  • 不能跨平台(不同系统的序列化格式可能不兼容)
  • 数据仍然可以被篡改

4.数据库存储(SQLite)

适用于大规模数据存储,如排行榜、库存管理等。安装 SQLite : 可以使用sqlite-net插件,或者Unity Database SQLite插件。

using System.Collections.Generic;
using SQLite4Unity3d;
using UnityEngine;

public class PlayerDatabase {
    private SQLiteConnection db;

    public PlayerDatabase(string databasePath) {
        db = new SQLiteConnection(databasePath);
        db.CreateTable<Player>();
    }

    public void AddPlayer(string name, int score) {
        db.Insert(new Player { Name = name, Score = score });
    }

    public List<Player> GetAllPlayers() {
        return db.Table<Player>().ToList();
    }
}

public class Player {
    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }
    public string Name { get; set; }
    public int Score { get; set; }
}

优点

  • 适用于大量数据
  • 可执行复杂查询

缺点

  • 需要额外插件支持
  • 学习成本较高
5.云端存储(Firebase, PlayFab, 自建服务器)

适用于多人游戏或数据同步。

using Firebase.Database;
using UnityEngine;

DatabaseReference dbReference = FirebaseDatabase.DefaultInstance.RootReference;

// 保存数据
public void SaveToFirebase(string userId, int score) {
    dbReference.Child("users").Child(userId).Child("score").SetValueAsync(score);
}

// 读取数据
public void LoadFromFirebase(string userId) {
    dbReference.Child("users").Child(userId).GetValueAsync().ContinueWith(task => {
        if (task.IsCompleted) {
            DataSnapshot snapshot = task.Result;
            int score = int.Parse(snapshot.Value.ToString());
            Debug.Log("Score: " + score);
        }
    });
}

优点

  • 适用于多人游戏
  • 数据可在不同设备同步

缺点

  • 需要联网
  • 可能需要额外的服务器成本
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Cherrylei2023

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值