using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using LitJson;
using System.Text;
using System.IO;
using UnityEngine.UI;
public class Model
{
public string key;
public string value;
}
public class BtnNameJson : MonoBehaviour
{
public static BtnNameJson Instance;
public static string strPath;
public List<Model> listModel = new List<Model>();
public List<GameObject> listBtns = new List<GameObject>();
private void Awake()
{
Instance = this;
strPath = Application.dataPath + "/BtnName.json";
}
void Start()
{
Invoke("Load", 1);
}
public void Load()
{
StreamReader streamReader = new StreamReader(strPath);
string str = streamReader.ReadToEnd();
JsonData jsdata = JsonMapper.ToObject(str);
listModel.Clear();
for (int i = 0; i < jsdata.Count; i++)
{
Model m = new Model { key = jsdata[i]["key"].ToString(), value = jsdata[i]["value"].ToString() };
listModel.Add(m);
}
for (int i = 0; i < listBtns.Count; i++)
{
foreach (var item in listModel)
{
if (item.key == listBtns[i].name)
{
listBtns[i].transform.GetComponentInChildren<InputField>().text = item.value;
}
}
}
}
public void Save()
{
listModel.Clear();
for (int i = 0; i < listBtns.Count; i++)
{
Model m = new Model() { key = listBtns[i].name, value = listBtns[i].transform.GetComponentInChildren<InputField>().text };
listModel.Add(m);
}
//找到当前路径
FileInfo file = new FileInfo(strPath);
//判断有没有文件,有则打开文件,,没有创建后打开文件
StreamWriter sw = file.CreateText();
//ToJson接口将你的列表类传进去,,并自动转换为string类型
string json = JsonMapper.ToJson(listModel);
//将转换好的字符串存进文件,
sw.WriteLine(json);
//注意释放资源
sw.Close();
sw.Dispose();
}
}
用
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class BtnChangeText : MonoBehaviour
{
InputField inp;
void Start()
{
BtnNameJson.Instance.listBtns.Add(gameObject);
inp = GetComponentInChildren<InputField>();
inp.onEndEdit.AddListener((string value) =>
{
BtnNameJson.Instance.Save();
});
}
}