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

public class TestPlayerPrefs
{
//单例模式实现
private static TestPlayerPrefs _instance;
public static TestPlayerPrefs Instance
{
get
{
if(_instance == null)
{
_instance = new TestPlayerPrefs();
}
return _instance;
}
}
public void setvalue(string key,int value)//保存int类型的值
{
PlayerPrefs.SetInt(key, value);
PlayerPrefs.Save();//数据保存到本地
}
public void setvalue(string key, float value)//保存int类型的值
{
PlayerPrefs.SetFloat(key, value);
PlayerPrefs.Save();//数据保存到本地
}
public void setvalue(string key, string value)//保存int类型的值
{
PlayerPrefs.SetString(key, value);
PlayerPrefs.Save();//数据保存到本地
}
public int GetInt(string key)
{
return PlayerPrefs.GetInt(key);
}
public string GetString(string key)
{
return PlayerPrefs.GetString(key);
}
public float GetFloat(string key)
{
return PlayerPrefs.GetFloat(key);
}
//数据的删除
public bool ContainsKey(string key)
{
return PlayerPrefs.HasKey(key);
}
public void Deletekey(string key)
{
if (ContainsKey(key))
{
//删除掉某个key对应的值
PlayerPrefs.DeleteKey(key);
PlayerPrefs.Save();
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//using UnityEngine.UI;

public class PlayerPrefsmanager : MonoBehaviour
{
//public Text hp;
//public Text gold;
//public Text mp;
//public Text name;
int age = 0;
float height = 0.0f;
string playername = “”;
// Start is called before the first frame update
void Start()
{

}// Update is called once per frame
void Update()
{//hp.text = TxtManager.Instance.playerdata.hp.ToString();//mp.text = TxtManager.Instance.playerdata.mp.ToString();//gold.text = TxtManager.Instance.playerdata.gold.ToString();//name.text = TxtManager.Instance.playerdata.name;//如果按下O键,修改变量的值if (Input.GetKeyDown(KeyCode.O)){//SetTestPlayerPrefs.Instance.setvalue("int_key", 20);TestPlayerPrefs.Instance.setvalue("float_key", 1.75f);TestPlayerPrefs.Instance.setvalue("string_key", "woerjianmin");}//如果按下P键,读取当前变量的值if (Input.GetKeyDown(KeyCode.P)){if (TestPlayerPrefs.Instance.ContainsKey("int_key")){age = TestPlayerPrefs.Instance.GetInt("int_key");}else{age = 0;}if (TestPlayerPrefs.Instance.ContainsKey("float_key")){height = TestPlayerPrefs.Instance.GetFloat("float_key");}else{height = 0f;}if (TestPlayerPrefs.Instance.ContainsKey("string_key")){playername = TestPlayerPrefs.Instance.GetString("string_key");}else{playername = "";}Debug.Log("age :" + age);Debug.Log("height :" + height);Debug.Log("name :" + playername);}//如果按下L键,删除某个键对应的值if (Input.GetKeyDown(KeyCode.L)){TestPlayerPrefs.Instance.Deletekey("int_key");TestPlayerPrefs.Instance.Deletekey("float_key");TestPlayerPrefs.Instance.Deletekey("string_key");}
}

}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;//IO流的命名空间

public class TxtManager
{
public Player playerdata;
private static TxtManager _instance;
public static TxtManager Instance
{
get
{
if (_instance == null)
{
_instance = new TxtManager();
}
return _instance;
}
}
public void Load(string Path)//传入参数:txt文本的路径
{
//方式一:
//TextAsset textAsset = Resources.Load(Path);//加载文本资源
//Debug.Log(textAsset.text);//输出文本中的所有内容
//方式二:
FileStream fs = new FileStream(Path, FileMode.Open);
StreamReader sr = new StreamReader(fs);
string str = sr.ReadToEnd();
//Debug.Log(str);
StringToPlayerType(str);
}
//分隔string内容,和玩家属性对应
public void StringToPlayerType(string content)
{
playerdata = new Player();//使用构造函数构建一个玩家对象,再次对属性赋值
string[] str = content.Split(’\n’);//通过\n换行符,得到现在的每一行的数据
//遍历每一行,属性赋值
for (int i = 0; i < str.Length; i++)
{
//Debug.Log(str[i]);//输出每一行的信息
//每一行进行逗号分隔
string[] columns = str[i].Split(’,’);
//得到两列,第一列是属性的名字,第二列是值
switch (columns[0])
{
case “name”:
playerdata.name = columns[1];
break;
case “hp”:
playerdata.hp = int.Parse(columns[1]);
break;
case “mp”:
playerdata.mp = int.Parse(columns[1]);
break;
case “gold”:
playerdata.gold = int.Parse(columns[1]);
break;
}
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class TestText : MonoBehaviour
{
public Text hp;
public Text gold;
public Text mp;
public Text PlayerName;
private void Start()
{
if (TestPlayerPrefs.Instance.ContainsKey(“PlayerData”))//如果数据被存储在本地,使用Key保存过了,直接读取本地玩家的偏好数据,赋值给玩家对象,再通过SetUI显示
{
string str = TestPlayerPrefs.Instance.GetString(“PlayerData”);
Debug.Log(“从本地读取玩家数据:” + str);
//FromJson的含义是:将json类型的字符串,转换为(player)的数据类型,进行赋值
TxtManager.Instance.playerdata = JsonUtility.FromJson(str);
setUI();
}
else
{
//TxtManager.Instance.Load(“Mytest2”);
//TxtManager.Instance.Load(@“C:\Users\Students_029\Desktop\woerjianmin\AngryBots2_Cinemachine\Unity20200908\Assets\Resources\Mytest2.txt”);
//Debug.Log(Application.dataPath);//会得到:\Users\Students_029\Desktop\woerjianmin\AngryBots2_Cinemachine\Unity20200908\Assets这一串
//string path = Application.dataPath + @"\Resources\Mytest2.txt"; //右斜杠写法
string path = Application.dataPath + “/Resources/Mytest2.txt”; //左斜杠写法
TxtManager.Instance.Load(path);
setUI();
}

}
private void Update()
{if (Input.GetKeyDown(KeyCode.A)){TxtManager.Instance.playerdata.hp -= 100;setUI();}if (Input.GetKeyDown(KeyCode.Q)){TxtManager.Instance.playerdata.mp -= 10;setUI();}if (Input.GetKeyDown(KeyCode.E)){TxtManager.Instance.playerdata.gold += 10;setUI();}if (Input.GetKeyDown(KeyCode.W))//按下w键:将玩家数据存储到jason中{//先用玩家偏好,通过key,将数据存储下来,转换为json字符串string str = JsonUtility.ToJson(TxtManager.Instance.playerdata);Debug.Log(str);TestPlayerPrefs.Instance.setvalue("PlayerData",str);//Debug.Log(JsonUtility.FromJson<Player>(str).name);}
}
void setUI()
{hp.text = TxtManager.Instance.playerdata.hp.ToString();mp.text = TxtManager.Instance.playerdata.mp.ToString();gold.text = TxtManager.Instance.playerdata.gold.ToString();PlayerName.text = TxtManager.Instance.playerdata.name;
}

}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player//封装的玩家类
{
//属性
public string name;//名字
public int gold;//金币数
public int hp;//血量值
public int mp;//法力值
}

xml文本

gold,500
hp,20000
mp,2000
name,woerjianming

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Xml.Serialization;//引入xml的命名空间

public class XmlMonster//怪物类
{
//属性名字和xml配置表中的属性名,保持一样
[XmlAttribute(AttributeName = “name”)]
public string name;
[XmlAttribute(AttributeName = “id”)]
public int id;
[XmlAttribute(AttributeName = “attack”)]
public int attack;
[XmlAttribute(AttributeName = “defense”)]
public float defense;
[XmlAttribute(AttributeName = “canMove”)]
public bool IsCanMove;

public override string ToString()
{return "id :" + id + "name :" + name + "attack :" + attack + "defense :"+ defense + "iscanmove :" + IsCanMove;
}

}
[XmlRoot(“Monsters”)]
public class Monsters//xml的根节点,对应的怪物的集合
{
[XmlElement(“monster”)]//每一行的信息
public List monster = new List();
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Xml.Serialization;//XML的命名空间
using System.IO;

public class XmlTest : MonoBehaviour
{
Monsters xmlMonster;//怪物类的集合列表
// Start is called before the first frame update
void Start()
{
//序列化的过程 — 转文件格式
//参数:根节点对应的类名Monsters
XmlSerializer serializer = new XmlSerializer(typeof(Monsters));
//加载Xml文件
//加载指定路径下的xml文件
FileStream fs = new FileStream(Application.dataPath + “/Resources/Monster.xml”, FileMode.Open);

    //反序列化的过程: 将文本类型的数据(xml中的数据)转换为类类型的数据xmlMonster =  serializer.Deserialize(fs) as Monsters;//遍历集合列表,输出所有的一行行的信息for (int i = 0; i < xmlMonster.monster.Count; i++){Debug.Log(xmlMonster.monster[i]);//重写了tostring方法}
}// Update is called once per frame
void Update()
{}

}

序列化和反序列化 加上json数据流转换相关推荐

  1. 序列化和反序列化(json和pickle)day18

    一.什么是序列化/反序列化 序列化就是将内存中的数据结构转换成一种中间格式存储到硬盘或者基于网络传输 反序列化就是将硬盘或者网络中传来的一种数据格式转换成内存中的数据结构 二.为什么要有 1.可以保持 ...

  2. 序列化和反序列化之json和pickle模块

    文章目录 一.json&pickle模块 1.什么是序列化? 2.为什么要序列化? 二.json 三.pickle 三.猴子补丁? 猴子补丁的功能(一切皆对象) monkey patch的应用 ...

  3. python之json序列化与反序列化

    文章目录 序列化就是将python中的字典转换为一种特殊的字符串(json) 那么反序列化就是,将json字符串转换为python字典 想输出真正的中文需要指定ensure_ascii=False,, ...

  4. json,pickle,shelve序列化和反序列化

    1.简介 ●  json:用于字符串 和 python简单数据类型(list,dict...)间进行转换:字符串<--->python简单数据类型 ●  pickle:用于python特有 ...

  5. JavaScript JSON序列化和反序列化

    文章目录 JavaScript JSON序列化和反序列化 概述 JSON序列化 JSON.stringify() 仅一个参数使用 使用2个参数 使用3个参数 其他 自定义toJson 序列化顺序 反序 ...

  6. JSON序列化和反序列化

    1.什么是json序列化和反序列化? json序列化:就是JavaBean对象转化为JSON格式的字符串. 反序列化:就是序列化的反方向,将字符串转化为JavaBean. 2.为什么要序列化和反序列化 ...

  7. LocalDateTime的JSON序列化和反序列化

    jackson的json中Date的序列化和反序列化 import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jac ...

  8. json 反序列化 父子类型_json类序列化与反序列化参考

    usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Web;usingSystem.Runtime.Ser ...

  9. 使用Newtonsoft.Json.dll(JSON.NET)动态解析JSON、.net 的json的序列化与反序列化(一)...

    在开发中,我非常喜欢动态语言和匿名对象带来的方便,JSON.NET具有动态序列化和反序列化任意JSON内容的能力,不必将它映射到具体的强类型对象,它可以处理不确定的类型(集合.字典.动态对象和匿名对象 ...

  10. Go进阶(7): JSON 序列化和反序列化

    1. json序列化和反序列化基础 json数据的序列化和反序列化是一种非常常见的方式,尤其是在http/rcp的微服务调试中. 基础语法 在 Go 中我们主要使用官方的 encoding/json  ...

最新文章

  1. 交互设计实用指南系列 – 我们眼中的交互设计
  2. 必须认识的http请求包
  3. linux 之 rpm 网站
  4. BEA-141281 unable to get file lock, will retry ...
  5. CCNA--增强型内部网关路由选择协议(EIGRP)
  6. LOJ bitset+分块 大内存毒瘤题
  7. python3.6.5安装步骤-Centos7 安装Python3.6.5
  8. 居中 html css
  9. 【语音去噪】基于matlab谱减法+最小均方+维纳滤波语音去噪【含Matlab源码 1542期】
  10. VirtualBox安装及使用说明和虚拟机安装XP系统图文教程
  11. 社区版PyCharm安装并创建Django项目
  12. 小米手机抢购背后的摩尔定律
  13. 服务器频繁重启怎么解决
  14. Mongodb 按照时间进行分组统计查询
  15. win10网络适配器不见了_win10网络适配器消失不见的解决方法
  16. Java中IO的快速复习(代码+注释)
  17. 一年多推行每日构建的经验总结
  18. 借助栈将一个带头节点的单链表倒置
  19. 蓝牙配对,解决蓝牙多次连接不上的问题
  20. 页面布局整理汇总,让你彻底搞明白多种布局的关系

热门文章

  1. 软件工程的标准定义:什么是软件工程?
  2. 教你一步一步用VPS
  3. 怎么判断苹果开发者账号是否认证了
  4. vlookup+left函数嵌套如何运用
  5. 什么是驱动程序?为什么要用驱动程序?
  6. 谷歌play商店_不断关闭时如何修复Google Play商店
  7. 传智播客dos命令_命令行英雄,原始播客
  8. 明翰英语教学系列之形容词与副词篇V0.1(持续更新)
  9. Jetson Xavier NX-EMMC重装系统
  10. fiddler证书下载(模拟器)