Unity Asset Bundle resources in packaging

Asset Bundle of action:

1, AssetBundle is a compressed package containing the model, texture, preform, sounds and even entire scene, can be loaded when the game is running;

2, AssetBundle preserved their mutual dependence;

3, can be compressed using the compression algorithm LZMA LZ4 and reduced size of the package, the faster the transmission network;

4, some content can be downloaded on AssetBundle which can reduce the size of the installation package;

What is AssetBundle

It can be attributed to two things:
1, which is present in a file on the hard disk. It can be called compressed. This archive can be thought of as a folder, which contains a number of documents. These files can be divided into two categories: serialized file and resource files. (Serialized files and source files)
Serialized File: resources are broken in one object, and finally be written into a single unified file (only one)
Resource Files: Some binary resources (images, sounds) are stored separately, fast and easy to load
2, which is a AssetBundle object, we can be loaded through code from a particular archive out of the object. This object contains all the content we had to add to the compressed inside, we can load it by using this object.

Asset Bundle resource package instance

Whether or UI resource model resource, it is best to first put them in Prefab, then made Assetbundle. Our model, for example, Assetbundle can put a model, you can also put multiple models, it is very flexible so most need to consider is the model space occupied by the problem.

Under Let's practice, the first two easily create 3D objects, Cube and Capsule, and made them Prefab, then go to the designated AssetBundle property resource, and here I these two models are packaged into model.ab package
( xxxa / xxx) xxxa here will generate a directory name is xxx, is behind the ab suffix, can develop their own.

After setting the properties, you can start to build AssetBundle package, first create a folder named Editor, this folder is a file extension is not specific editor packaged folder. Then we create an editor extension class CreateAssetbundles. Write the following code

using UnityEditor;
using System.IO;

public class CreateAssetbundles  {

    [MenuItem("AssetsBundle/Build AssetBundles")]
     static void BuildAllAssetBundles()//进行打包
    {
        string dir = "AssetBundles";
        //判断该目录是否存在
        if (Directory.Exists(dir) == false)
        {
            Directory.CreateDirectory(dir);//在工程下创建AssetBundles目录
        }
        //参数一为打包到哪个路径,参数二压缩选项  参数三 平台的目标
        BuildPipeline.BuildAssetBundles(dir, BuildAssetBundleOptions.None,BuildTarget.StandaloneWindows64);
    }
}

1, BuildAssetBundleOptions.None: use LZMA compression algorithm, compressed package is smaller, but the load times longer. Needs of the overall decompression prior to use. Once unpacked, the package will use LZ4 re-compression. When not require the use of resources overall decompression. You can use LZMA algorithm download time, once it has been downloaded, it will use LZ4 algorithm saved on the local.
2, BuildAssetBundleOptions.UncompressedAssetBundle: no compression, including big, fast loading
3, BuildAssetBundleOptions.ChunkBasedCompression: LZ4 use compression, the compression ratio is not high LZMA, but we can load the specified resource without extracting all.
Note the use of LZ4 compression can be achieved with no compression loading speed you may want comparable, but less than non-compressed files.

Back then click inside the Unity we just packed out extension button

Click our model is packed out, can be found AssetBundles directory under the project directory, there is a folder inside that we Scene packed files in AssetBundles, the suffix is ​​.ab.

AssetBundle loading

AssetBundle loading There are several ways to use LoadFromMemoryAsync loaded from memory, files can be loaded from a local use LoadFromFile, loaded from the server on the Web can be used UnityWbRequest. Let us look at the way these types of loads.
First, we can put the two models inside the Unity of Prefab Cube and Capsule removed, and then create a script hanging on Camera, open the script

The first loading (LoadFromMemoryAsync) loaded from memory
 

using UnityEngine;
using System.IO;
using System.Collections;
public class LoadFromFileExample : MonoBehaviour {

    IEnumerator  Start () {
        string path = "AssetBundles/scene/model.ab";
        //第一种加载AB的方式 LoadFromMemoryAsync
        //异步加载
        AssetBundleCreateRequest request = AssetBundle.LoadFromMemoryAsync(File.ReadAllBytes(path));
        yield return request;
        AssetBundle ab = request.assetBundle;
        //同步方式
        //AssetBundle ab=  AssetBundle.LoadFromMemory(File.ReadAllBytes(path));

         //使用里面的资源
        Object[] obj = ab.LoadAllAssets<GameObject>();//加载出来放入数组中
        // 创建出来
        foreach (Object o in obj)
        {
            Instantiate(o);
        }
    }
}

The second way (LoadFromFile), from a local

using UnityEngine;
using System.Collections;

public class LoadFromFileExample : MonoBehaviour {

    IEnumerator  Start () {
        string path = "AssetBundles/scene/model.ab";
        //第二种加载方式 LoadFromFile
        //异步加载
        AssetBundleCreateRequest request = AssetBundle.LoadFromFileAsync(path);
        yield return request;
        AssetBundle ab = request.assetBundle;
        //同步加载
        //AssetBundle ab = AssetBundle.LoadFromFile(path);

        //使用里面的资源
      Object[] obj = ab.LoadAllAssets<GameObject>();//加载出来放入数组中
        // 创建出来
        foreach (Object o in obj)
        {
            Instantiate(o);
        }
     }
}

The third way (UnityWbRequest) or loaded from a local server

using UnityEngine;
using System.Collections;
using UnityEngine.Networking;

public class LoadFromFileExample : MonoBehaviour {

    IEnumerator  Start () {
        //第三种加载方式   使用UnityWbRequest  服务器加载使用http本地加载使用file
        //string uri = @"file:///C:\Users\Administrator\Desktop\AssetBundleProject\AssetBundles\model.ab";
        string uri = @"http://localhost/AssetBundles\model.ab";
        UnityWebRequest request = UnityWebRequest.GetAssetBundle(uri);
        yield return request.Send();
        AssetBundle ab = DownloadHandlerAssetBundle.GetContent(request);

        //使用里面的资源
      Object[] obj = ab.LoadAllAssets<GameObject>();//加载出来放入数组中
        // 创建出来
        foreach (Object o in obj)
        {
            Instantiate(o);
        }
    }
}

We Model bag inside out and load a resource to be created in the scene. Unity is running this time you can see two models have each created out

Of course, you can create specific resources such as

 AssetBundle ab=AssetBundle.LoadFromFile("AssetBundles/scene/model.ab");
        GameObject go = ab.LoadAsset<GameObject>("Cube");
        Instantiate(go)

This realization Asset Bundle resource loaded

AssetBundle grouping strategy

1, the frequently updated resources on a single package which, with less frequently updated packet separator
2, the need to load the resources on which a packet
3, the packet can be other shared resource in a separate package inside
4, to package some of the resource need to be loaded into a small package
5, if there are two versions of the same for a resource may be considered v1 v2 v3 unity3dv1 unity3dv2 distinguished by the suffix

1, a logical entity group
a, a UI interface or all UI interface a packet (this interface, which the mapping and layout information of a packet)
B, a character or all characters a packet (the part inside the model and animation package)
C, All portions of a scene shared packet (including maps and models)
2, according to the type of packets
all sound resource packaged together, all shader packaged together, all of the models packaged together, all materials packaged together
3, using the packet according to
the use of all the resources within a certain time a labeled packet. Can follow the points points, all the resources needed to include a level role, textures, sounds, etc. labeled as a package. May be divided according to the situation, a resource required for a scene packet

Dependent package

意思就是例如有两个模型使用的都是同一个材质和贴图,那么模型和材质贴图之间就是依赖关系。如果我们这两个模型都单独打包出来那么就会打包出两份材质和贴图,这样包就会变大,那么我们如何解决呢,这里Unity里面自带有一种方式,那就是首先先把所依赖的材质和贴图单独打包到一个文件夹中,然后再分别打包两个需要依赖这个材质和贴图的模型。这样Unity就会去查找这个材质贴图,发现这个材质和贴图已经打包了出来,那么它就不会去重复的打包材质和贴图了,这样就大大减小了包的大小


上面一个是直接两个模型分别打包出来可以看到材质和贴图都分别打包了出来,分别都是63KB,而下面的是先将材质和贴图打包出来是62KB再将两个2KB的模型打包出来,总共也才64KB。

这就是Unity自带的依赖打包.
但是加载的时候模型、材质和贴图都要进行去加载,不然就会出现材质的丢失

using UnityEngine;

public class LoadFromFileExample : MonoBehaviour {

    void Start () {
        AssetBundle ab = AssetBundle.LoadFromFile("AssetBundles/cube.ab");
        AssetBundle abShare = AssetBundle.LoadFromFile("AssetBundles/share.ab");
        //GameObject go = ab.LoadAsset<GameObject>("Cube");
        //Instantiate(go);
        Object[] obj = ab.LoadAllAssets<GameObject>();//加载出来放入数组中
        //创建出来
        foreach (Object o in obj)
        {
            Instantiate(o);
        }
    }
}

AssetBundle的卸载

卸载有两个方面
1,减少内存使用
2,有可能导致丢失
所以什么时候去卸载资源
AssetBundle.Unload(true)卸载所有资源,即使有资源被使用着
1,在关卡切换、场景切换的时候
2,资源没被调用的时候
AssetBundle.Unload(false)卸载所有没用被使用的资源
个别资源怎么卸载
1,通过 Resources.UnloadUnusedAssets.
2,场景切换的时候

文件校验

文件校验可以在文件传输的时候保证文件的完整性,例如A在给我传输了一个文件之前会生成一个校验码,对于这个文件只会生成这一个唯一的校验码,只要传输给我的文件有一点不一样那么校验码就会完全不同。所以A在传输给我文件的时候会把文件和校验码都传输给我,当我取到这个文件的时候我也会使用和A同样一个算法去生成这个文件的校验码,然后拿这个值和A传输给我的校验码比对,如果一样说明这个文件是完整的,如果不一样那么就重新传输。下面是几个算法生成的校验值
CRC MD5 SHA1
相同点:
CRC、MD5、SHA1都是通过对数据进行计算,来生成一个校验值,该校验值用来校验数据的完整性。
不同点:

  1. 算法不同。CRC采用多项式除法,MD5和SHA1使用的是替换、轮转等方法;
  2. 校验值的长度不同。CRC校验位的长度跟其多项式有关系,一般为16位或32位;MD5是16个字节(128位);SHA1是20个字节(160位);
  3. 校验值的称呼不同。CRC一般叫做CRC值;MD5和SHA1一般叫做哈希值(Hash)或散列值;
  4. 安全性不同。这里的安全性是指检错的能力,即数据的错误能通过校验位检测出来。CRC的安全性跟多项式有很大关系,相对于MD5和SHA1要弱很多;MD5的安全性很高,不过大概在04年的时候被山东大学的王小云破解了;SHA1的安全性最高。
  5. 效率不同,CRC的计算效率很高;MD5和SHA1比较慢。
  6. 用途不同。CRC一般用作通信数据的校验;MD5和SHA1用于安全(Security)领域,比如文件校验、数字签名等。

转载自:https://www.jianshu.com/p/5d4145cd900c

Guess you like

Origin blog.csdn.net/qq_38721111/article/details/88992913