在开发中保存数据是一个很重要的操作,在Unity开发中有很多的保方式,最近接触到一种用JSon文件保存的方式。记录下来便于以后回顾使用。

  关于数据有两种:

  (1)初始数据:在开发过程中开发者已经保存好的数据。也就是一些项目的初始数据,这些数据有开发者自己他编写的,这些数据需要应用开始使用直接读取就好了。

开发者可以直接创建json文件将一些初始化的数据添加进去就OK了;

  (2)修改后的引用数据:在应用在产生的数据还需要记录下来的部分,就需要在程序运行中调用保存了;

     1)//定义一个UnityJSon 类

public class UnityJSon : MonoBehaviour {     

    private string fileName;    // 定义一个string类型的变量 (文件名)

    private string path;        //定义有个string类型的变量(创建路径名)

    void Start ()

{       

    path = Application.dataPath + "/Resources";      //给变量赋值指定路径

     fileName = "Student.json";                             //赋值名

   if (!Directory .Exists (path ))                                //判断路径是否存在不存在就创建一个;     

    {            

    Directory.CreateDirectory(path);        

   }     

    fileName = Path.Combine(path, fileName);     //将文件名和路径合并

    if (!File .Exists (fileName ))     //判断文 是否已经存在不存在就创建一个文件;

    {            

   FileStream fs = File.Create(fileName);            

   fs.Close();        

    }     

     Saves();      // 保存文件的方法;     

   Read();    // 读取文件的方法;

}    

void Saves()    

{         string json = JsonUtility.ToJson(PersonContainer.Instace);    

     File.WriteAllText(fileName, json, Encoding.UTF8);    //utf8 万国码避免乱码; 

}    

void Read ()    

{     

        string json = File.ReadAllText(fileName, Encoding.UTF8);      

        PersonContainer.Instace = JsonUtility.FromJson<PersonContainer>(json);     

       for (int i=0; i< PersonContainer .Instace .personList .Count;i++ )      

      {          

       Debug.Log(PersonContainer.Instace.personList[i]);      

      }   

 }    

 void Update () {     }

 

}

[System.Serializable]

public class PersonContainer

{    

     public List<Person> personList;  

    private static  PersonContainer instance;

    public static PersonContainer Instace

    {        

      get   {   if (instance ==null )    

                        { 

                        instance = new PersonContainer();

                         }            

                        return instance;        

             }        

      set  {    instance = value;  

             }    

    }

    public  PersonContainer ()   

  {        

  personList = new List<Person>();

        personList.Add(new Person(("zhangsan"), 10));

        personList.Add(new Person("lisi", 11));  

   }

}

    [System.Serializable]

    public class Person

{     public  string name;    public  int age;

    public Person ()     {     }    

public Person (string name ,int age)   

{         this.name = name;       

  this.age = age;    

}   

  public override string ToString()  

   {       

  return this.name + "," + this.age;   

  }

}

: