Unity數據的保存(JSon)


  在開發中保存數據是一個很重要的操作,在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;   

  }

}

:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM