Unity5.3更新了assetbundle的打包和加载api,下面简单介绍使用方法及示例代码。
在Unity中选中一个prefab查看Inspector窗口,有两个位置可以进行assetbundle的标记。
第一个为assetBundleName,如果这里不是None,则这个资源会记录到AssetDatabase里,使用BuildAssetBundles打包时,会自动将AssetBundleName一致的资源打到一个包中。
第二个为Variant,可用于区分不同分辨率的资源。如果在abName=S的情况下,variant有None也有HD,打ab包时会报错,如果variant有指定,则同一abName的资源的variant不能为None。
// 此api用于打包所有标记了AssetBundleName的资源
public static AssetBundleManifest BuildAssetBundles(
string outputPath,
BuildAssetBundleOptions assetBundleOptions = BuildAssetBundleOptions.None,
BuildTarget targetPlatform = BuildTarget.WebPlayer
);
// 此api用于打包指定的资源
public static AssetBundleManifest BuildAssetBundles(
string outputPath,
AssetBundleBuild[] builds,
BuildAssetBundleOptions assetBundleOptions = BuildAssetBundleOptions.None,
BuildTarget targetPlatform = BuildTarget.WebPlayer
);
其中,AssetBundleBuild数组参数,用于指定资源,AssetBundleBuild有三个属性,分别指定assetBundleName,variant,资源路径等。
以下为打包及加载部分代码:大部分参考了雨凇MOMO的文章《UGUI研究院之全面理解图集与使用(三)》,做了部分修改。
1 #define USE_ASSETBUNDLE 2 3 using UnityEngine; 4 using System.Collections; 5 using UnityEngine.UI; 6 using UnityEditor.VersionControl; 7 8 public class UIMain : MonoBehaviour{ 9 10 AssetBundle assetbundle = null; 11 void Start () 12 { 13 CreatImage(loadSprite("flag_blue")); 14 CreatImage(loadSprite("flag_yellow")); 15 } 16 17 private void CreatImage(GameObject gobj ){ 18 Sprite sprite = gobj.GetComponent<SpriteRenderer>().sprite as Sprite; 19 GameObject go = new GameObject(sprite.name); 20 go.layer = LayerMask.NameToLayer("UI"); 21 go.transform.parent = transform; 22 go.transform.localScale= Vector3.one; 23 Image image = go.AddComponent<Image>(); 24 image.sprite = sprite; 25 image.SetNativeSize(); 26 } 27 28 private GameObject loadSprite(string spriteName){ 29 #if USE_ASSETBUNDLE 30 if(assetbundle == null) 31 assetbundle = AssetBundle.LoadFromFile(Application.streamingAssetsPath +"/flagbundle"); 32 return assetbundle.LoadAsset(spriteName) as GameObject; 33 #else 34 return Resources.Load<GameObject>("Sprite/" + spriteName); 35 #endif 36 } 37 38 }