Unity3d resources encryption and cache Loading

Source: Internet
Author: User

First, we should despise the unity3d document writers for being extremely irresponsible. The correct sample code has not been updated until the post ends.

// C# Example    // Builds an asset bundle from the selected objects in the project view.    // Once compiled go to "Menu" -> "Assets" and select one of the choices    // to build the Asset Bundle        using UnityEngine;    using UnityEditor;using System.IO;    public class ExportAssetBundles {        [MenuItem("Assets/Build AssetBundle Binary file From Selection - Track dependencies ")]        static void ExportResource () {            // Bring up save panel            string path = EditorUtility.SaveFilePanel ("Save Resource", "", "New Resource", "unity3d");            if (path.Length != 0) {                // Build the resource file from the active selection.                Object[] selection = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets);                BuildPipeline.BuildAssetBundle(Selection.activeObject, selection, path, BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets);                Selection.objects = selection;            FileStream fs = new FileStream(path,FileMode.Open,FileAccess.ReadWrite);byte[] buff = new byte[fs.Length+1];fs.Read(buff,0,(int)fs.Length);buff[buff.Length-1] = 0;fs.Close();File.Delete(path);string BinPath = path.Substring(0,path.LastIndexOf('.'))+".bytes"; //FileStream cfs = new FileStream(BinPath,FileMode.Create);cfs.Write(buff,0,buff.Length);buff =null;cfs.Close();//string AssetsPath = BinPath.Substring(BinPath.IndexOf("Assets"));//Object ta = AssetDatabase.LoadAssetAtPath(AssetsPath,typeof(Object));//              BuildPipeline.BuildAssetBundle(ta, null, path);}        }        [MenuItem("Assets/Build AssetBundle From Selection - No dependency tracking")]        static void ExportResourceNoTrack () {            // Bring up save panel            string path = EditorUtility.SaveFilePanel ("Save Resource", "", "New Resource", "unity3d");            if (path.Length != 0) {                // Build the resource file from the active selection.                BuildPipeline.BuildAssetBundle(Selection.activeObject, Selection.objects, path);            }        }    }

Convert the packaged file into a binary file and add a byte encryption.

After the bytes file is generated, select it and use "Assets/Build AssetBundle From Selection-No dependency tracking" to package it again.

 

using UnityEngine;using System.Collections;using System;public class WWWLoadTest : MonoBehaviour{    public string BundleURL;    public string AssetName;    IEnumerator Start()    {          WWW www =WWW.LoadFromCacheOrDownload(BundleURL,2);                yield return www;                TextAsset txt = www.assetBundle.Load("characters",typeof(TextAsset)) as TextAsset;                byte[]  data = txt.bytes;                byte[] decryptedData = Decryption(data);        Debug.LogError("decryptedData length:"+decryptedData.Length);        StartCoroutine(LoadBundle(decryptedData));    }        IEnumerator LoadBundle(byte[] decryptedData){                AssetBundleCreateRequest acr = AssetBundle.CreateFromMemory(decryptedData);                    yield return acr;        AssetBundle bundle = acr.assetBundle;                Instantiate(bundle.Load(AssetName));            }        byte[] Decryption(byte[] data){        byte[] tmp = new byte[data.Length-1];        for(int i=0;i<data.Length-1;i++){            tmp[i] = data[i];            }        return tmp;            }    }

WWW. LoadFromCacheOrDownload is used to download and cache resources. Pay attention to the later version number parameter. If you replace the resource but do not update the version number, the client will still load the files in the cache.

Www. assetBundle. Load ("characters", typeof (TextAsset) as TextAsset // characters is the name of the encrypted file

AssetBundleCreateRequest acr = AssetBundle. CreateFromMemory (decryptedData );

This sentence is the most boring on the official website. AssetBundle. CreateFromMemory clearly returns AssetBundleCreateRequest but writes AssetBundle on the official website. AssetBundleCreateRequest is an asynchronous loading and must be loaded using coroutine. Here I am with multiple brothers.

.

 

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.