赞
踩
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- using UnityEngine.UI;
- using System.IO;
-
- //将类序列化到文件中,同时序列化到编辑器中
- [System.Serializable]
- public class PlayerCoin{
- public int count;
- public string name;
- public bool isWinner;
- }
-
- //存储一系列类数据,必须创建一个链表,链表必须存在在类中,才能被序列化
- public class PlayerCoinList
- {
- public List<PlayerCoin> playerCoinList = new List<PlayerCoin>();
- }
-
- public class DataSaveManager : MonoBehaviour
- {
- public PlayerCoinList list = new PlayerCoinList();
- PlayerCoin knight; //保存骑士
- PlayerCoin wizzard; //保存巫师
-
- public Text knightCoin; //骑士的金币数量的显示文字
- public Text wizzardCoin; //巫师的金币数量的显示文字
-
-
- // Start is called before the first frame update
- void Start()
- {
- //创建json数据,只需要创建一次就行
- // GenerateData();
- //数据的读取
- LoadDate();
- }
-
- // Update is called once per frame
- void Update()
- {
-
- }
-
- #region 生成实例并赋初值
- void GenerateData()
- {
- knight = new PlayerCoin();
- knight.count = 0;
- knight.name = "Knight";
- knight.isWinner = false;
-
- wizzard = new PlayerCoin();
- wizzard.count = 0;
- wizzard.name = "Wizzard";
- wizzard.isWinner = false;
-
- list.playerCoinList.Add(knight);
- list.playerCoinList.Add(wizzard);
- }
- #endregion
-
- #region 金币增加按钮事件
- //按钮事件:点击按钮时金币数量的增加
- public void OnClickCoin(string _player)
- {
- if (_player.Equals("Knight"))
- {
- knight.count += 1;
- knightCoin.text = knight.count.ToString();
- }else if (_player.Equals("Wizzard"))
- {
- wizzard.count += 1;
- wizzardCoin.text = wizzard.count.ToString();
- }
- }
- #endregion
-
- #region 数据存储
- void SaveData()
- {
- //将list转化成一个json文件
- string json = JsonUtility.ToJson(list,true);
- //设置保存的路径
- string filePath = Application.streamingAssetsPath + "/playCoinList.json";
- //文件的写入
- using(StreamWriter sw = new StreamWriter(filePath))
- {
- sw.WriteLine(json);
- sw.Close();
- sw.Dispose();
- }
- }
-
- #endregion
-
- #region 保存按钮事件
-
- public void OnClickQuit()
- {
- //数据的存储
- SaveData();
- //退出游戏
- UnityEditor.EditorApplication.isPlaying = false; //编辑器下退出游戏
- Application.Quit();
- }
- #endregion
-
- #region 数据的读取
-
- void LoadDate()
- {
- string json;
- string filePath = Application.streamingAssetsPath + "/playCoinList.json";
-
- //检测json文件是否存在
- if (File.Exists(filePath))
- {
- //json文件存在,直接进行数据读取
- using (StreamReader sr = new StreamReader(filePath))
- {
- json = sr.ReadToEnd();
- sr.Close();
- }
- //将json文件转化为内存中的一个变量
- list = JsonUtility.FromJson<PlayerCoinList>(json);
-
- //将读取的数据赋值
- knight = list.playerCoinList[0];
- wizzard = list.playerCoinList[1];
-
- //更新文本显示
- knightCoin.text = knight.count.ToString();
- wizzardCoin.text = wizzard.count.ToString();
- }
- else
- {
- //json文件不存在,先创建,再进行读取
- GenerateData();
- }
-
-
- }
- #endregion
-
- }
脚本挂载在manager这个空物体上,对应的按钮添加对应的事件(注意:在金币增加按钮事件的添加时:输入的string的字符串必须与代码中一致)
链接:https://pan.baidu.com/s/1a9x6Jmbh8o9L1Q54tqED6Q
提取码:jl98
(ps:在哔哩哔哩找了一个视频学习的,视频链接也放这了:【UNITY教程】第1集 使用JSON存储数据_哔哩哔哩_bilibili)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。