Unity3d Automatic file Update system

Source: Internet
Author: User

Unity3d Automatic file Update systemtime 2014-08-27 17:47:10 csdn Blog original http://blog.csdn.net/x_studying/article/details/38873727

After the game content changes, generally do not want to let the player download the entire game pack reinstall, because this will drain a large number of players. All game updates are required. The updated content includes data, resources, and code.

Basic principle:

1. Package The files that need to be updated into Assetbundle files and calculate the CRC values for each file.

The following code exports the selected file as a Assetbundle file, writes the CRC value of each file to the Crc.txt file, establishes a class in the editor directory, and copies the following code. You can export selected files in the project directory.

public class Exportassetbundles {

[MenuItem ("Assets/build assetbundle from Selection respective-track dependencies")]

static void Exportresourcerespective ()

{

Bring up Save panel

String path = Editorutility.savefilepanel ("Save Resource", "", "New Resource", "Unity3d");

String Dirpath = path. Substring (0,path. LastIndexOf ("/") +1);

string filename = path. Substring (path. LastIndexOf ("/") +1);

if (path. Length! = 0) {

#if unity_android

String targetDir = "Android/";

Buildtarget targetbuild = buildtarget.android;

#elif Unity_iphone

String targetDir = "iphone/";

Buildtarget targetbuild = Buildtarget.iphone;

#elif Unity_standalone_win

String targetDir = "standalonewindows/";

Buildtarget targetbuild = buildtarget.standalonewindows;

#endif

Jsdocument.jsnode node = new Jsdocument.jsnode ("root");

document.snode[] nodes = Node.putchildren ("Filehash", Selection.objects.Length);

for (int i=0;i<selection.objects.length;i++)

{

String name = selection.objects[i].name+ ". Unity3d";

UINT CRC = 0;

if (! Directory.Exists (Dirpath+targetdir))

Directory.CreateDirectory (Dirpath+targetdir);

Buildpipeline.buildassetbundle (Selection.objects[i],new object[]{selection.objects[i]}, Dirpath+targetDir+name, Out crc,buildassetbundleoptions.collectdependencies,targetbuild);

Nodes[i].put ("name", name);

Nodes[i].put ("CRC", CRC);

}

System.IO.File.WriteAllText (dirpath+targetdir+filename+ ". Crc.txt", node.tojsonstring ());

}

}

}

2. A resource update server is required to upload the exported assetbundle files and CRC files to the resource update server. You can use a simple HTTP server. For example Nginx.

3. Before the client enters the game, first request the Crc.txt file to the update server. Then find the Crc.txt file from the Local disk directory and check the list of files that need to be updated. Then download the files that need to be updated from the server. This way, if the server does not change the file, it needs to be downloaded only once.

4. The latest Crc.txt file to local for the next query.

The following code demonstrates the 3,4 step, where

Engine.Instance.server_datapath = Server.

Engine.Instance.local_datapath = application.persistentdatapath+ "/;

public static IEnumerator Updatedatafromserver (UpdateProgress up)

{

string server_datapath = Engine.Instance.server_datapath;

string local_datapath = Engine.Instance.local_datapath;

byte[] Server_crc_data = null;

Dictionary<string,long> filehash_server=new dictionary<string, long> ();

Dictionary<string,long> filehash_local=new dictionary<string, long> ();

list<string> needupdatefile = new list<string> ();

Debug.Log ("Load Server Filehash");

using (www www = new www (server_datapath+ "crc.txt"))

{

yield return www;

if (! String.IsNullOrEmpty (Www.error))

{

Debug.Log ("Load filehash Failed");

Up (1.0f);

Yield break;

}

Jsdocument.jsnode node = new Jsdocument.jsnode ("Filehash", Www.text);

document.snode[] data = Node.getchildren ("Filehash");

for (int i=0;i<data. length;i++)

{

Filehash_server[data[i].get ("name", "")] = Data[i].get ("CRC", (long) 0);

}

Server_crc_data = www.bytes;

}

Debug.Log ("Load Local Filehash");

Loading a file from the local MD5 table may not

Try

{

Jsdocument.jsnode node = new Jsdocument.jsnode ("Filehash", System.IO.File.ReadAllText (local_datapath+ "Crc.txt"));

document.snode[] data = Node.getchildren ("Filehash");

for (int i=0;i<data. length;i++)

{

Filehash_local[data[i].get ("name", "")] = Data[i].get ("CRC", (long) 0);

}

}

catch (Exception e)

{

Debug.Log (E.message);

}

Debug.Log ("Check filehash");

Calculate files that need to be updated

foreach (keyvaluepair<string,long> data in Filehash_server)

{

Update the required files

if (!filehash_local. ContainsKey (data. Key) | | Filehash_local[data. Key]! = data. Value)

{

Needupdatefile.add (data. Key);

}

}

Debug.Log ("Update File");

Download and store

for (int i=0;i<needupdatefile.count;i++)

{

using (www www = new www (server_datapath+needupdatefile[i]))

{

yield return www;

byte[] bytes = NULL;

if (! String.IsNullOrEmpty (Www.error))

{

Debug.Log (Www.error);

Yield break;

}

Else

{

bytes = Www.bytes;

}

Up ((float) i/needupdatefile.count);

String path = local_datapath+ Needupdatefile[i];

Debug.Log (path);

FileStream fs = new FileStream (path,filemode.create);

Fs. Write (bytes,0,bytes. Length);

Fs. Flush ();

Fs. Close ();

Save

BinaryWriter writer;

FileInfo T =new FileInfo (local_datapath+ needupdatefile[i]);

if (!t.exists)

//              {

writer = new BinaryWriter (T.open (FileMode.OpenOrCreate));

//              }

Else

//              {

T.delete ();

writer = new BinaryWriter (T.open (FileMode.Create));

//              }

Writer. Write (bytes);

Writer. Close ();

}

}

Debug.Log ("Save filehash");

if (needupdatefile.count>0)

{

Save the most recent file MD5 value table

FileStream fs = new FileStream (local_datapath+ "Crc.txt", FileMode.Create);

Fs. Write (Server_crc_data,0,server_crc_data. Length);

Fs. Flush ();

Fs. Close ();

BinaryWriter writer;

FileInfo T =new FileInfo (local_datapath+ "Crc.txt");

if (!t.exists)

{

writer = new BinaryWriter (T.open (FileMode.Create));

}

Else

{

T.delete ();

writer = new BinaryWriter (T.open (FileMode.Create));

}

Writer. Write (Server_crc_data);

Writer. Close ();

Debug.Log (local_datapath+ "Crc.txt");

}

}

5. Loading the assetbundle that have been updated to the local storage, note that unity3d the same file can only have one assetbundle in memory, so we synchronize the loading of the same file. (Loadrefcount).

static hashset<string> Loadrefcount = new hashset<string> ();

public delegate void Delegateloadfinish (Gameobject go);

public static IEnumerator Loadmodel (String res,delegateloadfinish onloadfinish)

{

Gameobject resobject = resources.load<gameobject> ("cards/" +res);

if (Resobject!=null)

{

Onloadfinish ((gameobject) gameobject.instantiate (resobject));

Yield break;

}

If a resource is included, returns

while (Loadrefcount.contains (res))

{

Yield return true;

}

Loadrefcount.add (RES);

Debug.Log (engine.instance.local_datapath+res+ ". Unity3d");

Assetbundlecreaterequest Crclocalbundle = Assetbundle.createfrommemory (

System.IO.File.ReadAllBytes (engine.instance.local_datapath+res+ ". Unity3d"));

Yield return crclocalbundle;

{

Gameobject cardobject = gameobject.instantiate (crcLocalBundle.assetBundle.mainAsset) as Gameobject;

CrcLocalBundle.assetBundle.Unload (FALSE);

Onloadfinish (Cardobject);

}

Loadrefcount.remove (RES);

}

Unity3d Automatic file Update system

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.