AssetBundle打包
1.在资源的AssetLabel,设置资源的BundleName以及BundleVariant,然后进行打包。
BuildAssetBundles的时候自动收集打AB。
AssetBundleManifest BuildAssetBundles(string outputPath, BuildAssetBundleOptions assetBundleOptions, BuildTarget targetPlatform);
2.定义AssetBundleBuild[]数组,只打包这些资源,但需要注意的是也要打包依赖项。
AssetBundleManifest BuildAssetBundles(string outputPath, AssetBundleBuild[] builds, BuildAssetBundleOptions assetBundleOptions, BuildTarget targetPlatform);
using UnityEditor;
using System.IO;
public class CreateAssetBundles //进行AssetBundle打包
{
[MenuItem("Assets/Build AssetBundles")]
static void BuildAllAssetBundles()
{
string dir = "AssetBundles";
if (Directory.Exists(dir) == false)
{
Directory.CreateDirectory(dir);
}
BuildPipeline.BuildAssetBundles(dir, //路径必须创建
BuildAssetBundleOptions.ChunkBasedCompression, //压缩类型
BuildTarget.StandaloneWindows64);//平台
}
}
None | Build assetBundle without any special option.(LAMA压缩,压缩率高,解压久) |
UncompressedAssetBundle | Don't compress the data when creating the asset bundle.(不压缩,解压快) |
ChunkBasedCompression | Use chunk-based LZ4 compression when creating the AssetBundle. (压缩率比LZMA低,解压速度接近无压缩) |
AssetBundle加载
1.LoadFromMemory(LoadFromMemoryAsync)
2.LoadFromFile(LoadFromFileAsync)
3.UnityWebRequest
第一种
IEnumerator Start()
{
string path = "AssetBundles/wall.unity3d";
AssetBundleCreateRequest request =
AssetBundle.LoadFromMemoryAsync(File.ReadAllBytes(path));
yield return request;
AssetBundle ab = request.assetBundle;
GameObject wallPrefab = ab.LoadAsset<GameObject>("Cube");
Instantiate(wallPrefab);
}
第二种
IEnumerator Start()
{
string path = "AssetBundles/wall.unity3d";
AssetBundleCreateRequest request = AssetBundle.LoadFromFileAsync(path);
yield return request;
AssetBundle ab = request.assetBundle;
GameObject wallPrefab = ab.LoadAsset<GameObject>("Cube");
Instantiate(wallPrefab);
}
第三种
IEnumerator Start()
{
string uri = @"http://localhost/AssetBundles/cubewall.unity3d";
UnityWebRequest request = UnityWebRequest.GetAssetBundle(uri);
yield return request.Send();
AssetBundle ab = DownloadHandlerAssetBundle.GetContent(request);
GameObject wallPrefab = ab.LoadAsset<GameObject>("Cube");
Instantiate(wallPrefab);
}
AssetBundle卸载
AssetBundle.Unload(bool),T
true卸载所有资源
false只卸载没使用的资源,而正在使用的资源与AssetBundle依赖关系会丢失,调用Resources.UnloadUnusedAssets可以卸载。或者等场景切换的时候自动调用Resources.UnloadUnusedAssets。