unity储存系统

用json来实现玩家基本数据的储存

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;

public static class SaveSystem
{
    #region Prefs
    //保存数据
    public static void SaveByPlayerPrefs(string key,object data)
    {
        var josn=JsonUtility.ToJson(data,true);//将物体转为josn true方便人阅读
        PlayerPrefs.SetString(key, josn);//注册数据
        PlayerPrefs.Save();//保存在硬盘
    }
    //加载数据
    public static string LoadForPlayerPrefs(string key)
    {
        return PlayerPrefs.GetString(key);//读取数据
    }
    #endregion
    #region JSON
    //储存数据
    public static void SaveByJson(string saveFileName,object data)
    {
        var json=JsonUtility.ToJson(data);
        var path = Path.Combine(Application.persistentDataPath,saveFileName);//unity中自带申请储存位置的函数 Application.persistentDataPath
        try
        {
            Debug.Log($"susscessfully save data to {path}");
            File.WriteAllText(path,json);//WriteAllText 创建文本  文件路径 文件内容 覆写内容

        }
        catch(System.Exception exception)//获取系统异常处理
        {
           #if UNITY_EDITOR//只在unity中运行
            Debug.LogError($"Failed to save data to {path}.\n{exception}");
               #endif
        }
    }
    //加载数据
    public static T LoadFromJson<T>(string saveFileName)
    {
        var path = Path.Combine(Application.persistentDataPath, saveFileName);//unity中自带申请储存位置的函数
        try
        {
            var json=File.ReadAllText(path);//读取文件
            var data = JsonUtility.FromJson<T>(json);//转化json文件数据
            return data;
        }
        catch (System.Exception exception)//获取系统异常处理
        {
           #if UNITY_EDITOR//只在unity中运行
            Debug.LogError($"Failed to load data from {path}.\n{exception}");
          #endif
            return default;
        }
    }
    //删除数据
    public static void DeleteSaveFile(string saveFileName)
    {
        var path = Path.Combine(Application.persistentDataPath, saveFileName);//unity中自带申请储存位置的函数
        try
        {
           File.Delete(path);
        }
        catch (System.Exception exception)//获取系统异常处理
        {
          #if UNITY_EDITOR//只在unity中运行
            Debug.LogError($"Failed to Delete data from {path}.\n{exception}");
         #endif
     
        }
    }
    //检查数据是否存在
    public static bool SaveFileExists(string saveFileName)
    {
        var path = Path.Combine(Application.persistentDataPath, saveFileName);//unity中自带申请储存位置的函数
        return  File.Exists(path);//检查玩家数据是否存在
    }
    #endregion
}

如果我想要本地玩家的数据做一个排行榜,使用方法

using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;

public class ScoreManager : Singleton<ScoreManager>
{

    #region Score
    public int Score => score;

    int score = 0;//显示分数
    int currentScore = 0;//实际分数
    Vector3 scoreTextScale = new Vector3(1.2f, 1.2f, 1.2f);//文本矩形变大
    [SerializeField] float waitTime = 1f;
    WaitForSeconds waitForSeconds;

    private void Start()
    {
        waitForSeconds=new WaitForSeconds(waitTime);
    }
    //增加分数
    public void AddScore(int volume)
    {
        currentScore+=volume;
        StartCoroutine(nameof(AddScoreCoroutine));
    }
    //实现分数逐步增加 协程
    IEnumerator AddScoreCoroutine()
    {

        Debug.Log("分数增加");
        ScoreDisplay.ScaleText(scoreTextScale);
        while (score <=currentScore)
        {
            score++;
            ScoreDisplay.UpdataScore(score);
            yield return waitForSeconds;
        }
        ScoreDisplay.ScaleText(Vector3.one);//文本矩形框复原
    }
    #endregion
    #region hight Score
    [System.Serializable]  public class PlayerScore//封装玩家数据
    {
        public int score;
        public string playerName;
        public PlayerScore(int score, string playerName)//构造函数 构造函数的作用就是初始化一个新创建的对象,并在使用对象前设置对象的属性,也就是实例化;
        {
            this.score = score;
            this.playerName = playerName;
        }
    }
    [System.Serializable] public class PlayerScoreData//玩家数据集合
    {
       public  List<PlayerScore> List=new List<PlayerScore>();
    }
    readonly string SaveFileName = "player_score.json";
    string playerName= "No Name";
    public bool isHasNewHeighScore =>score> LoadPlayerScoreData().List[9].score;//当前得分大于列表最后一个数据 就为真
    //存储玩家数据
  public void SavePlayerScoreData()
    {
        var playerScoreData = LoadPlayerScoreData();
        playerScoreData.List.Add(new PlayerScore(score, playerName));
        playerScoreData.List.Sort((x,y)=>y.score.CompareTo(x.score));//实现列表降序排列
        SaveSystem.SaveByJson(SaveFileName, playerScoreData);
    }
    //加载玩家数据
   public PlayerScoreData LoadPlayerScoreData()
    {
        var playerScoreData=new PlayerScoreData();
        if(SaveSystem.SaveFileExists(SaveFileName))//是否有玩家数据
        {
             playerScoreData=SaveSystem.LoadFromJson<PlayerScoreData>(SaveFileName); 
        }
        else
        {
            while(playerScoreData.List.Count<10)
            {
                playerScoreData.List.Add(new PlayerScore(0,playerName));
            }
            SaveSystem.SaveByJson(SaveFileName,playerScoreData);
        }
        return playerScoreData;
    }
    //更改玩家名字
    public void SetPlayerName(string newPlayerName)
    {
        playerName=newPlayerName;
    }
    #endregion

}

详细的看

[Unity] 存档系统 Part 2 | JSON | Unity初学者系列教程 | 数据存取 | 数据持久化 | 存档读档 | Save&Load_哔哩哔哩_bilibili

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值