序列化和反序列化 加上json数据流转换

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))
    {
        //Set
        TestPlayerPrefs.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()
{
    
}

}

猜你喜欢

转载自blog.csdn.net/bellainvan/article/details/108485262