原博客:https://blog.youkuaiyun.com/lzhq1982/article/details/19237031
通过一下午的学习终于弄懂了Json的使用,直接放源码
1.存的数据的基本类型
using UnityEngine;
using System.Collections;
public class Player {
private string name;
private int grade;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public int Grade
{
get
{
return grade;
}
set
{
grade = value;
}
}
}
2.数据存在列表里
using UnityEngine;
using System.Collections.Generic;
public class PlayerList {
public List<Player> players = new List<Player>();
}
上面两个类不继承于MOON
3.管理类,取数据和存数据
using UnityEngine;
using System.Collections;
using System.IO;
using LitJson;
using UnityEditor;
using System.Collections.Generic;
public class PlayerManager : MonoBehaviour {
// public static PlayerManager m_instacne;
PlayerList m_playerlist = new PlayerList();
private bool bFind;
private string filePath;
// Use this for initialization
private void Update()
{
if (Input.GetKeyDown(KeyCode.A))
{
Player player = new Player();
int temp2 = Random.Range(2, 32);
string str = "player" + temp2;
player.Name = str;
int temp = Random.Range(1, 32);
player.Grade = temp;
SavePlayerData(player);
}
}
private void Start()
{
ShowPlayers();
}
/// <summary>
/// 存入数据
/// </summary>
/// <param name="data"></param>
public void SavePlayerData(Player data)
{
filePath = Application.dataPath + @"/Resources/Settings/JsonPlayer.txt";
if (!File.Exists(filePath))
{
m_playerlist = new PlayerList();
m_playerlist.players.Add(data);
}
else
{
bool bFind = false;
for (int i = 0; i < m_playerlist.players.Count; ++i)
{
Player saveData = m_playerlist.players[i];
if (data.Name == saveData.Name)
{
saveData.Grade = data.Grade;
bFind = true;
break;
}
}
if (!bFind)
m_playerlist.players.Add(data);
}
FileInfo file = new FileInfo(filePath);
StreamWriter sw = file.CreateText();
string json = JsonMapper.ToJson(m_playerlist);
sw.WriteLine(json);
sw.Close();
sw.Dispose();
#if UNITY_EDITOR
AssetDatabase.Refresh();
#endif
}
/// <summary>
/// 取到数据
/// </summary>
public void ShowPlayers()
{
TextAsset s = Resources.Load("Settings/JsonPlayer") as TextAsset;
if (!s)
return;
string strData = s.text;
m_playerlist = JsonMapper.ToObject<PlayerList>(strData);
for(int i=0;i<m_playerlist.players.Count;i++)
{
Debug.Log(m_playerlist.players[i].Name+" "+m_playerlist.players[i].Grade);
}
}
}
json数据存放的路径是Resources/Settings/JsonPlayer.txt,按这个路径创建即可