【AssetBundle】AB包的序列化与反序列化

序列化AB包

    /// <summary>
    ///标记选择的东西   给选择的东西赋AB包名字
    /// </summary>
    [MenuItem("Test/FlagAssetbundle")]
    public static void FlagAssetbundle()
    {
        Object go = Selection.activeObject;//拿到选择的东西
        var s = AssetDatabase.GetAssetPath(go);//拿到选择物体的路径
        AssetImporter import = AssetImporter.GetAtPath(s);//拿到资源对象的导入器
        import.assetBundleName = "Myflag";//在导入器下改资源 AB包 的名字
        AssetDatabase.SaveAssets();//保存
    }
    //菜单按钮更新功能
    [MenuItem("Test/BuildAssetBundles")]
    public static void BuildAssetBundles()
    {
        AssetDatabase.Refresh();//刷新
        //创建S路径文件夹    
        Directory.CreateDirectory( Application.streamingAssetsPath+"/AssetBundles");
        //创建AB包   参数一:AB包创建路径     2:创建AB包的类型:压缩,不压缩,无      3:适配机器类型
        BuildPipeline.BuildAssetBundles(Application.streamingAssetsPath + "/AssetBundles", BuildAssetBundleOptions.None, BuildTarget.StandaloneWindows);
        //手机移动端只能在S目录下   AB包尽量在S目录下     S目录只能读不能写
    }

反序列化AB包

using System.Collections;
using UnityEngine;

public class AssetBundles : MonoBehaviour
{
    private void Start()
    {
        StartCoroutine(F2());//调用协程
    }
    //异步 解析 加载 AB包  反序列化
    //协程函数
    public IEnumerator F2()
    {
        //异步解压
        AssetBundleCreateRequest req = AssetBundle.LoadFromFileAsync(Application.dataPath + "/AssetBundles/spere ");
        yield return req;//等待异步解压  反序列化完成  AB包
        AssetBundle ab=req.assetBundle;
        //异步拿到   资源对象
        var req1=ab.LoadAssetAsync<GameObject>("Assets/Resources/Prefab/2.prefab");
        yield return req;//等待异步完成
        Object ab2 = req1.asset;
        Instantiate(ab2);//实例出物体
        ab.Unload(false);//拿出东西不用AB包了   清除掉
    }

    // 同步解析 加载 AB包  反序列化
    public void F1()
    {
        //加载 解析 AB包中小球的依赖材质  放在内存中  系统会自动拿到材质并赋值
        AssetBundle ab2 = AssetBundle.LoadFromFile(Application.dataPath + "/AssetBundles/mat1");
        //加载 解析 AB包  放在内存中
        AssetBundle ab = AssetBundle.LoadFromFile(Application.dataPath + "/AssetBundles/spere");
        //拿到AB包中的资源  路径  拿出来用
        GameObject go = ab.LoadAsset<GameObject>("Assets/Resources/Prefab/2.prefab");
        //实例化出cube
        Instantiate(go);
        //拿出东西不用AB包了   清除掉
        ab.Unload(false);
        ab2.Unload(false);
    }
}

猜你喜欢

转载自blog.csdn.net/m0_74022070/article/details/131822439