unity移动端数据持久化

xiaoxiao2021-02-28  124

数据持久化就是将数据保存到本地,每次打开都读取它,当保存的重新写入。 比如说最简单的应用就是你要进行网路链接的时候需要输入端口号和IP地址。 当应用关闭再打开的时候你希望能保存你上次输入的IP和端口号。这就需要将数据保存起来。 本地化保存的方法有两种: 1.一种是使用PlayerPrefs类来解决,在ios,android,window都存储在不同的地方。比如说Windows就存储在注册表里 2.第二种是本地文件读写xml或者读写txt,window平台没啥好说的用ios平台举个例子: 首先是文件的保存位置     pathFile = Application.persistentDataPath + "/redapple.txt"; 其中Application.persistentDataPath根据平台的不同路径也不同 写入数据:      string  pathFile = Application.persistentDataPath + "/redapple.txt";//文件路径   public GameObject IPInputObj = null;//ip地址输入  public GameObject PortInputObj = null;//端口设置   public string[] pData;//存放端口和ip地址的数组    void Start ()      {         //初始化数据         InitData();     }     void InitData()     {         pathFile = Application.persistentDataPath + "/redapple.txt";         print (pathFile);         /         pData = new string[2];         if (!ReadData())         {             OnBtnSet();         }                       }   //写入设置    public void OnBtnSet()     {         SetWindowData();     }   //读取数据   bool ReadData()     {         bool ret = false;         if (ReadFromFile(pathFile, 2, ref pData))         {             strIP = pData[0];             strPort = pData[1];             ret = true;         }         return ret;     }    //写入文件    public bool WriteToFile(string path,int length,string[] data)     {         StreamWriter sw= new StreamWriter(path);         sw.Write("");         for(int i =0;i<length;i++)         {             sw.WriteLine(data[i]);         }         sw.Close();         return true;     }    //写入数据    bool WriteData(string strip, string strport)     {         bool ret = false;         pData[0] = strip;         pData[1] = strport;         if (WriteToFile(pathFile, 2, pData))         {             ret = true;         }         return ret;     }    //输入框显示数据    void SetWindowData()     {                      IPInputObj.GetComponentInChildren<InputField>().text = strIP;                     PortInputObj.GetComponentInChildren<InputField>().text = strPort;              }
转载请注明原文地址: https://www.6miu.com/read-69806.html

最新回复(0)