today, this article is actually a commonplace problem, similar articles on the internet abound, here I just do a detailed summaryconvenient for everyone to better, faster grasp, of course, if there are insufficient places to welcome correction!!!
we believe that in the development process,Some files will inevitably be savedLocalize the operation on the client.
such as: Configuration file, state file,assetbundle files, etc. ..
recentI was always asked:
1.save an XML in the client, can read the data inside, but can not be modified, or even a correction error ...
2. I manipulate the files on my computer (XML, text,Assetbundle, JSON) It's all fine.However, the generation of package Generation APK, IPA run a variety of problems,
either the data cannot be read or the data cannot be manipulated ...
Where exactly are the symptoms of these problems? And how to solve it?
In fact, it is the applicability of the path of file preservation between platforms, and some paths are not universal on each platform.
Here I summarize the path operations in unity in the following ways:
Create the Resources folder in the project root directory to save the file.
You can use Resources.load ("file name, note: Do not include the file suffix name"), and load the objects in the folder .
Note: This party can implement the file implementation of "Delete and change" operation, butcannot be changed after packaging.
Two. Save the file directly on the project root path
use Application.datapath directly to read the file.
Note: the mobile side is not access rights.
three.Create the Streamingassets folder in the project root directoryto save the file.
1. You can use the Application.datapath to read the file for operation.
[C #]Plain Text view copy code
#if Unity_editor
String filepath = Application.datapath + "/streamingassets" + "/my.xml";
#elif Unity_iphone
String filepath = Application.datapath + "/raw" + "/my.xml";
#elif unity_android
string filepath = "jar:file://" + Application.datapath + "!/assets/" + "/my.xml;
#endif
2. Use Application.streamingassetspath directly to read the file.
Note: This method can be implemented in the PC/MAC computer to implement the "adding and removing changes" and other operations, but on the mobile side only support read operations.
four. Use Application.Persistentdatapath to operate the file ( recommended )
the file exists in the phone sandbox because the file cannot be stored directly,
1. Save to this location by direct download of the server, alsonew resources can be updated with MD5 code-to-download
2. No server, only indirectRead and write locally from a file streamApplication.persistentdatapath file, and then go through theapplication.Persistentdatapathto read the operation.
Note: In Pc/mac computer and Android and ipad, Ipone can do any of the files, in addition things in this directory on iOS can be automatically backed up by icloud .
Five. Using Application.temporarycachepath to manipulate files
operation mode with the aboveapplication.Persistentdatapathsimilar. Not automatically backed up by icloud except on iOS.
is the exact location of several files in the path of the PC
<ignore_js_op>
in fact, inI have already sent an article in front of thepath in Unity corresponds to the path in each platform"article,Let 's take a look at a detailed understanding of the specific path that unity can operate in the mobile platform.
have direct to the platform corresponding to the path yo, convenient debugging view.
OK, Unity path use and attention points are summed up, now or send some dry material to everyone, there are detailed comments, are commonly used in the development of things
1. The operation of the file class, mainly is the text stream read operations of some things (including Assetbundle)
FileHelper.cs
[C #]Plain Text view copy code
Using Unityengine;
Using System.Collections;
Using System.IO;
Using System.Collections.Generic;
Using System;
<summary>
Use the Application.persistentdatapath method to create files, read and write XML files.
Note Application.persistentdatapath No "/" symbol at the end
</summary>
public class Filehelper:monobehaviour
{
<summary>
Create folders dynamically.
</summary>
<returns>the folder.</returns>
<param name= "path" > File creation directory .</param>
<param name= "FolderName" > folder name (without symbols) .</param>
public string CreateFolder (String path,string FolderName)
{
string folderpath = Path+foldername;
if (! Directory.Exists (FolderPath))
{
Directory.CreateDirectory (FolderPath);
}
return folderpath;
}
<summary>
Create a file.
</summary>
<param name= "path" > Full folder path .</param>
<param name= The name of the "name" > File .</param>
<param name= "Info" > What to write .</param>
public void CreateFile (string path,string name,string info)
{
File stream Information
StreamWriter SW;
FileInfo t = new FileInfo (path+name);
if (!t.exists)
{
If this file does not exist, create the
SW = T.createtext ();
}
Else
{
Open if this file is present
SW = T.appendtext ();
}
Write information in line form
Sw. WriteLine (info);
Close the stream
Sw. Close ();
Destroying a stream
Sw. Dispose ();
}
<summary>
Read the file.
</summary>
<returns>the file.</returns>
<param name= "path" > Full folder path .</param>
<param name= "Name" > read the name of the file .</param>
Public ArrayList LoadFile (string path,string name)
{
Read in the form of a stream
StreamReader SR =null;
try{
sr = File.OpenText (path+name);
}catch (Exception e)
{
Path and name not found file will return empty directly
return null;
}
String line;
ArrayList arrlist = new ArrayList ();
while (line = Sr. ReadLine ()) = null)
{
A row of reads
Storing the contents of each row in an array-linked list container
Arrlist. ADD (line);
}
Close the stream
Sr. Close ();
Destroying a stream
Sr. Dispose ();
Returns the array-linked list container
return arrlist;
}
Write model to Local
IEnumerator loadassetbundle (string url)
{
www w = new www (URL);
Yield return w;
if (W.isdone)
{
Byte[] model = w.bytes;
int length = model. Length;
Write model to Local
Createassetbundlefile (Application.persistentdatapath, "Model.assetbundle", model,length);
}
}
<summary>
Get all file sizes under File
</summary>
<param name= "FilePath" ></param>
<returns></returns>
public int getallfilesize (string filePath)
{
int sum = 0;
if (! Directory.Exists (FilePath))
{
return 0;
}
DirectoryInfo dti = new DirectoryInfo (FilePath);
Fileinfo[] fi = dti. GetFiles ();
foreach (FileInfo f in FI)
{
Sum + = Convert.ToInt32 (f.length/1024);
}
directoryinfo[] di = dti. GetDirectories ();
if (di. Length > 0)
{
for (int i = 0; i < di. Length; i++)
{
Sum + = Getallfilesize (di. FullName);
}
}
return sum;
}
<summary>
Gets the specified file size
</summary>
<param name= "FilePath" ></param>
<param name= "FileName" ></param>
<returns></returns>
public int GetFileSize (string FilePath, String FileName)
{
int sum = 0;
if (! Directory.Exists (FilePath))
{
return 0;
}
Else
{
FileInfo Files = new FileInfo (@FilePath + FileName);
Sum + = Convert.ToInt32 (files.length/1024);
}
return sum;
}
void Createassetbundlefile (string path, string name, byte[] info, int length)
{
File stream Information
StreamWriter SW;
Stream SW;
FileInfo t = new FileInfo (path + "//" + name);
if (!t.exists)
{
If this file does not exist, create the
SW = T.create ();
}
Else
{
Open if this file is present
SW = T.append ();
Return
}
Write information in line form
Sw. Write (info, 0, length);
Close the stream
Sw. Close ();
Destroying a stream
Sw. Dispose ();
}
Read local Assetbundle file
IEnumerator loadassetbundlefromlocal (string path, string name)
{
Print ("file:///" + path + "/" + name);
www w = new www ("file:///" +path + "/" + name);
Yield return w;
if (W.isdone)
{
Instantiate (W.assetbundle.mainasset);
}
}
<summary>
Delete the file.
</summary>
<param name= "path" > Delete full folder path .</param>
<param name= "name" > Delete file name .</param>
public void DeleteFile (string path, string name)
{
File.delete (path + name);
}
<summary>
deleting files
</summary>
<param name= "Path" ></param>
<param name= "Filesname" ></param>
<returns></returns>
public bool Deletefiles (string path, String filesname)
{
BOOL Isdelete = false;
Try
{
if (directory.exists (path))
{
if (file.exists (path + "\" + filesname))
{
File.delete (path + "\ \" + filesname);
Isdelete = true;
}
}
}
Catch
{
return isdelete;
}
return isdelete;
}
}
2. Random Operation class
RandomHelper.cs
[C #]Plain Text view copy code
Using Unityengine;
Using System.Collections;
<summary>
Random Operation class
</summary>
public class Randomhelper
{
private static char[] constant = {' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 ', ' A ', ' B ', ' C ', ' d ', ' e ', ' f ', ' g ', ' H ' ', ' I ', ' j ', ' K ', ' l ', ' m ', ' n ', ' o ', ' P ', ' Q ', ' R ', ' s ', ' t ', ' u ', ' V ', ' w ', ' x ', ' y ', ' z ', ' A ', ' B ', ' C ', ' D ', ' E ', ' F ', ' G ', ' H ', ' I ', ' J ', ' K ', ' L ', ' M ', ' N ', ' O ', ' P ', ' Q ', ' R ', ' S ', ' T ', ' U ', ' V ', ' W ', ' X ', ' Y ', ' Z '};
<summary>
String random
</summary>
<param name= "Length" > number of digits to be randomly </param>
<returns></returns>
public string generaterandomnumber (int Length)
{
System.Text.StringBuilder newrandom = new System.Text.StringBuilder (62);
for (int i = 0; i < Length; i++)
{
Newrandom.append (Constant[random.range (0,62));
}
return newrandom.tostring ();
}
private static char[] Constant1 = {' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 '};
<summary>
Digital random
</summary>
<param name= "Length" > number of digits to be randomly </param>
<returns></returns>
public string generatenumber (int Length)
{
System.Text.StringBuilder newrandom = new System.Text.StringBuilder (10);
for (int i = 0; i < Length; i++)
{
Newrandom.append (Constant1[random.range (0, 10)]);
}
return newrandom.tostring ();
}
<summary>
String array random
</summary>
<param name= "chars" > Arrays </param>
<param name= "Length" > Random number of digits </param>
<returns></returns>
public string Getstrrandomsurname (string[] chars, int Length)
{
int count = chars. Length;
System.Text.StringBuilder newrandom = new System.Text.StringBuilder (count);
for (int i = 0; i < Length; i++)
{
Newrandom.append (Chars[random.range (0, Count)]);
}
return newrandom.tostring ();
}
<summary>
String * Intercept
</summary>
<param name= "str" > Strings </param>
<returns></returns>
Public string[] Getstringtolist (String str)
{
Return str. Split (' * ');
}
}
Unity in the mobile platform, file operation path detailed