using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
using LitJson;
using System.IO;
using System.Text.RegularExpressions;
using System;
public class ItemDatabase : MonoBehaviour
{
private JsonData itemData;
private List<Item> database = new List<Item>();
void Awake()
{
// Item my = new Item(1, "213", 212);
// Get(my);
}
private void Start()
{
itemData = JsonMapper.ToObject(File.ReadAllText(Application.dataPath + "/ItemAssets/123.json"));
SaveItemData();
ReadItemData();
}
void ReadItemData()
{
foreach (Item info in database )
{
print("ID:" + info.ID + " Name:" + info.Name + " Level:" + info.Level);
}
}
void SaveItemData()
{
for (int i = 0; i < itemData.Count; i++)
{
database.Add(new Item((int)itemData[i]["ID"], itemData[i]["Name"].ToString(), (int)itemData[i]["Level"]));
}
}
public Item GetItemData(int _id)
{
for (int i = 0; i < database.Count; i++)
{
if (_id == database[i].ID)
{
return database[i];
}
}
return null;
}
void Get(Item p) {
string path = Application.dataPath + "/ItemAssets/123.json";
database .Add(p);
//写入数据
string jsonData = "[\n";
for (int i = 0; i < database .Count; i++)
{
if (i == database .Count - 1)
{
jsonData += JsonMapper.ToJson(database [i]) + "\n";
break;
}
jsonData += JsonMapper.ToJson(database [i]) + "\n,";
}
jsonData += "]";
//转码
Regex reg = new Regex(@"(?i)\\[uU]([0-9a-f]{4})");
jsonData = reg.Replace(jsonData, delegate (Match m) { return ((char)Convert.ToInt32(m.Groups[1].Value, 16)).ToString(); });
File.WriteAllText(path, jsonData); }
}
public class Item
{
public int ID { get; set; }
public string Name { get; set; }
public int Level { get; set; }
//构造函数
public Item(int _id, string _name, int _level)
{
this.ID = _id;
this.Name = _name;
this.Level = _level;
}
}
json文件
[
{"ID":1,"Name":"213","Level":212}
]