JSon存储和读取数据unity

 可以通过json来加载数据,笔记写起来自己看的,有需要的可单独问

using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.UI;
/// <summary>
/// Json存储读取数据
/// </summary>
public class Json_SaveRead : MonoBehaviour
{
    private Button Input_Btn;
    public Text name_text;
    //public InputField user_text;
    public Image User_image;
    private void Start()
    {
        Init();
        ReadJson();        
       //Debug.Log(GetPersonInfo(2).Name);
       name_text.text = GetPersonInfo(1).Name;
       User_image.sprite = Resources.Load<Sprite>("Icon/"+ GetPersonInfo(1).Icon);
        Input_Btn = transform.Find("Button (Legacy)").GetComponent<Button>();
        Input_Btn.onClick.AddListener(()=>
        {          
            SaveData(); 
        });
    }
    Data My_Data = new Data();
    Person knight;
    Person wizzard;
    /// <summary>
    /// 存储数据
    /// </summary>
    void SaveData()
    {      
        //将数据转成json
        string js = JsonUtility.ToJson(My_Data,true);
        //获取到项目路径
        string fileUrl = Application.streamingAssetsPath + "/jsonInfo.json";
        //  Debug.Log(fileUrl);
       
        //打开或者新建文档
        using (StreamWriter sw = new StreamWriter(fileUrl))
        {
            //保存数据
            sw.WriteLine(js);
            //关闭文档
            sw.Close();
            sw.Dispose();
        }
    }
    /// <summary>
    /// 读取Json
    /// </summary>
    void ReadJson()
    {
        string json;
        string filepath = Application.streamingAssetsPath + "/jsonInfo.json";
        using (StreamReader sr = new StreamReader(filepath))
        {
            json = sr.ReadToEnd(); 
            sr.Close();
        }
        My_Data = JsonUtility.FromJson<Data>(json);//转换成数据        
    }
    private Dictionary<int, Person> personInfos = new Dictionary<int, Person>();
    public void Init()
    {
        knight = new Person();
        wizzard = new Person();
        knight.ID = 1;
        knight.Name = "头盔";
        knight.Icon = "2";
        knight.type = 2;
        knight.price = 100;
        knight.tips = "防御无敌";
        wizzard.ID = 2;
        wizzard.Name = " 匕首";
        wizzard.Icon = "1";
        wizzard.type = 2;
        wizzard.price = 100;
        wizzard.tips = "锋利无比";
        My_Data.person1.Add(knight);
        My_Data.person1.Add(wizzard);
        //这样的写法需要去查找每一个,太繁琐,我们直接用一个字典通过查询id就可以识别出所有的
        //knight
        //Debug.Log(My_Data.person1.Count);
        //for (int i = 0; i < My_Data.person1.Count; i++)
        //{
        //    name_text.text = My_Data.person1[1].Name;
        //}
        for (int i = 0; i < My_Data.person1.Count; i++)
        {
            personInfos.Add(My_Data.person1[i].ID, My_Data.person1[i]);
        }
    }
    /// <summary>
    /// 这样就可以通过id来获取到里面的所有内容
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public Person GetPersonInfo(int id)
    {
        if (personInfos.ContainsKey(id))
        {
            return personInfos[id];
        }
        return null;
    }
}
[System.Serializable]
public class Person
{
    public int ID;
    public string Name;
    public string Icon;
    public int type;
    public int price;
    public string tips;
}
[System.Serializable]
public class Data
{
    //public Person[] person;
    public List<Person> person1 = new List<Person>();
}

 

登陆注册代码

using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.UI;

public class Login : MonoBehaviour
{
    #region 登录信息
    public InputField Log_name;
    public InputField Log_password;
    #endregion
    #region 注册信息
    public InputField register_name;
    public InputField register_password;
    public InputField tworegister_password;
    #endregion
    public Image login;//登录页面
    public Image register;//注册页面
    //提示信息
    public Text tip;
    private Dictionary<string, string> allAccount;
    // Use this for initialization
    private void Awake()
    {
        allAccount = new Dictionary<string, string>();
    }
    void Start()
    {
        ReadJson();
    }

    public void Loginbtn()
    {
        string username = Log_name.text;
        string password = Log_password.text;
        if (username == "" || password == "")
        {
            tip.text = "用户名或密码为空,请重新输入";
            return;
        }
        else if (allAccount.ContainsKey(username))
        {
            if (password == allAccount[username])
            {
                tip.text = "登录成功!!";
                return;
            }
            else
            {
                tip.text = "密码错误!!";
                return;
            }
        }
        else
        {
            tip.text = "用户名或密码错误";
        }
    }
    //注册按钮
    public void Registerbtn()
    {
        login.gameObject.SetActive(false);
        register.gameObject.SetActive(true);
    }
    //注册
    public void Signupbtn()
    {
        string name = register_name.text;
        string password = register_password.text;
        string password2 = tworegister_password.text;
        Debug.Log(name);
        if (password == "" || name == "")
        {
            print("用户名和密码不能为空!!");
            return;

        }
        else if (allAccount.ContainsKey(name))
        {
            //如果用户名和已知的重复时
            print("该用户名已经被用了,请换一个吧!");
            return;
        }
        else if (password != password2)
        {
            //如果两次输入密码不一致时
            print("两次输入的密码不一样");
            return;
        }
        else
        {
            allAccount.Add(name, password);
           
            SaveData();
            print("注册成功!!");
        }
    }
    void SaveData()
    {
        //将数据转成json
        string js = JsonUtility.ToJson(allAccount, true);
        //获取到项目路径
        string fileUrl = Application.streamingAssetsPath + "/jsonInfo.json";
        //  Debug.Log(fileUrl);
        //打开或者新建文档
        using (StreamWriter sw = new StreamWriter(fileUrl))
        {
            //保存数据
            sw.WriteLine(js);
            //关闭文档
            sw.Close();
            sw.Dispose();
        }

    } 
    public void returnlogin()
    {
        login.gameObject.SetActive(false);
        register.gameObject.SetActive(true);
    }
   
    /// <summary>
    /// 读取Json
    /// </summary>
    void ReadJson()
    {
        string json;
        string filepath = Application.streamingAssetsPath + "/jsonInfo.json";
        using (StreamReader sr = new StreamReader(filepath))
        {
            json = sr.ReadToEnd();
            sr.Close();
        }
        allAccount = JsonUtility.FromJson<Dictionary<string, string>>(json);//转换成数据

    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值