AssetBundle的自动标记、打包以及几种加载方式

这里写自定义目录标题


因为打包是需要打成ab格式的所以要在Unity的AssetBundle处更改GameObject的名字以及后缀。`

[MenuItem("AB包/标记名字")]
    public static void CreatName()
    {
        Object[] seles = Selection.objects;
        foreach (Object item in seles)
        {
            //获取选中单个对象的路径 
            string mPath = AssetDatabase.GetAssetPath(item);
            //通过路径修改该对象的名称和后缀
            AssetImporter asset = AssetImporter.GetAtPath(mPath);

            Debug.Log(mPath);

            int start = 7;
            int end = mPath.IndexOf(".");
            int len = end - start;
            //获取名字(字符串截取)
            string bundleName = mPath.Substring(start, len);
            Debug.LogError(bundleName);
            //修改名字
            asset.assetBundleName = bundleName;
            asset.assetBundleVariant = "ab";
            //保存
            asset.SaveAndReimport();
        }
    }

    [MenuItem("AB包/删除标记")]
    public static void DeleteBundleName()
    {
        object[] seles = Selection.objects;
        foreach (Object item in seles)
        {
            string mPath = AssetDatabase.GetAssetPath(item);
            AssetImporter asset = AssetImporter.GetAtPath(mPath);
            asset.assetBundleName = null;
            asset.SaveAndReimport();
        }
    }

    public static string GetOnPath()
    {
        return Application.dataPath + "/../" + "AssetBundles";
    }

    /// <summary>
    /// 判断是否有路径,如果没有则创建路径
    /// </summary>
    /// <param name="outPath"></param>
    public static void IsCreatDirectory(string outPath)
    {
        if (!Directory.Exists(outPath))
        {
            Directory.CreateDirectory(outPath);
        }
    }

    [MenuItem("AB包/打包Windows")]
    public static void CreatWindodws()
    {
        string path = GetOnPath() + "/DoWindows";
        IsCreatDirectory(path);
        BuildPipeline.BuildAssetBundles(path, BuildAssetBundleOptions.None, BuildTarget.StandaloneWindows64);
    }

这样就把GameObject打成AB包的名字改为自己的名字了,并且打包选项已经可以显示在设置栏上面(注意:这个脚本要放在Editor文件夹里面)。

打完AB包下面就是加载AB包的几种方式了
第一种加载方式:从文件中加载`

//ab包路径
        string path = "AssetBundle/DoWindows/prefabs/Cubewall.ab";
        string UIPath = "AssetBundle/DoWindows/material/materialwall.ab";
        string tupian = "AssetBundle/DoWindows/uilogin/微信图片_20210712084114.ab";
        //第一种加载方法——从文件中加载
        AssetBundle ab = AssetBundle.LoadFromFile(path);
        //使用里面的资源
        GameObject CubeObj = ab.LoadAsset<GameObject>("cubeWall");
        GameObject obj = Instantiate(CubeObj);

从文件中异步加载

        string path = "AssetBundle/DoWindows/prefabs/Cubewall.ab";
        string UIPath = "AssetBundle/DoWindows/material/materialwall.ab";
        string tupian = "AssetBundle/DoWindows/uilogin/微信图片_20210712084114.ab";
        //异步加载
        AssetBundleCreateRequest request = AssetBundle.LoadFromFileAsync(path);
        //等待加载完成
        yield return request;
        //获得AssetBundle对象
        AssetBundle ab = request.assetBundle;
        //使用里面的资源
        GameObject CubeObi = ab.LoadAsset<GameObject>("cubewall");
        //实例化
        GameObject obj = Instantiate(CubeObi);

异步加载必须使用协程

第二种加载方式:从内存中加载

        string path = "AssetBundle/DoWindows/prefabs/Cubewall.ab";
        string UIPath = "AssetBundle/DoWindows/material/materialwall.ab";
        string tupian = "AssetBundle/DoWindows/uilogin/微信图片_20210712084114.ab";
                //从内存中加载——第二种加载方式
        byte[] by = File.ReadAllBytes(path);
        //获得AssetBundle对象
        AssetBundle ab = AssetBundle.LoadFromMemory(by);
        //使用里面的资源
        GameObject CubeObj = ab.LoadAsset<GameObject>("cubewall");
        GameObject obj = Instantiate(CubeObj);

从内存中进行异步加载

        //第二种加载方式——从内存中异步加载
        byte[] by = File.ReadAllBytes(path);
        byte[] b = File.ReadAllBytes(UIPath);
        byte[] tu = File.ReadAllBytes(tupian);

        AssetBundleCreateRequest request = AssetBundle.LoadFromMemoryAsync(by);
        AssetBundleCreateRequest request1 = AssetBundle.LoadFromMemoryAsync(b);
        AssetBundleCreateRequest request2 = AssetBundle.LoadFromMemoryAsync(tu);

        yield return request;//等待异步加载完成

        AssetBundle ab = request.assetBundle;
        AssetBundle ui = request1.assetBundle;
        AssetBundle tupia = request2.assetBundle;

        GameObject CubeObj = ab.LoadAsset<GameObject>("cubewall");
        Material a = ui.LoadAsset<Material>("materialwall");
        Texture2D tu1 = tupia.LoadAsset<Texture2D>("微信图片_20210712084114");

        a.SetTexture("acc", tu1);
        GameObject obj = Instantiate(CubeObj);
        obj.GetComponent<MeshRenderer>().material = a;


        //WenJian();
        //Coroutine wenjianyibu = StartCoroutine(WenJianYiBu());
        //NeiCun();
        //Coroutine neicunyibu = StartCoroutine(NeiCunYiBu());
        //Coroutine wwwyibu = StartCoroutine(wwwLoadAsset());
        //Coroutine web = StartCoroutine(WebRequest());

异步加载必须写在协程里,然后开启协程使用。

第三种加载方式:从www中加载

/// <summary>
    /// 第三种方式——从www中加载
    /// </summary>
    /// <returns></returns>
    IEnumerator wwwLoadAsset()
    {
        string path1 = @"http://192.168.41.220/AssetBundle/DoWindows/prefabs/uiloginmodule.ab";
        string path3 = @"http://192.168.41.244/AssetBundle/DoWindows/prefabs/uiloginmodle.ab";
        //string path2 = @"file:G:/Unity3DProject/shisanzhouqi/AssetBundle/DoWindows/DoWindows";
        WWW www = WWW.LoadFromCacheOrDownload(path3, 2);
        yield return www;
        if (string.IsNullOrEmpty(www.error) == false)
        {
            Debug.LogError(www.error);
        }
        AssetBundle ab = www.assetBundle;
        GameObject cubeobj = ab.LoadAsset<GameObject>("UILoginModule");
        GameObject obj = Instantiate(cubeobj, GameObject.Find("Canvas").transform);
        obj.transform.localPosition = new Vector3(0, 0, 0);
    }

从www中加载必须在协程中写方法,并且开启协程才能使用

//开启协程
Coroutine wwwyibu = StartCoroutine(wwwLoadAsset());
//关闭协程
StopCoroutine((wwwLoadAsset())

第四种加载方式:从WebRequest中加载(最常用的加载方式、可以加载依赖)

/// <summary>
    /// 第四种加载方式——最常用的加载方式
    /// </summary>
    IEnumerator WebRequest()
    {
        string path2 = @"http://192.168.215.117/AssetBundles/DoWindows/prefabs/uiloginmodle.ab";
        string path3 = @"http://192.168.215.117/AssetBundles/DoWindows/DoWindows";
        UnityWebRequest request = UnityWebRequestAssetBundle.GetAssetBundle(path2);
        yield return request.SendWebRequest();
        if (string.IsNullOrEmpty(request.error) == false)
        {
            Debug.LogError(request.error);
            yield break;
        }
        AssetBundle ab = DownloadHandlerAssetBundle.GetContent(request);
        GameObject obj = ab.LoadAsset<GameObject>("UILoginModle");


        //加载依赖
        UnityWebRequest request2 = UnityWebRequestAssetBundle.GetAssetBundle(path3);
        yield return request2.SendWebRequest();
        if (string.IsNullOrEmpty(request2.error) == false)
        {
            Debug.LogError(request2.error);
            yield break;
        }
        AssetBundle ab1 = DownloadHandlerAssetBundle.GetContent(request2);
        //获得清单文件
        AssetBundleManifest mainifest = ab1.LoadAsset<AssetBundleManifest>("AssetBundleManifest");
        //获取清单文件中的预设体的依赖项
        string[] strs = mainifest.GetAllDependencies("prefabs/uiloginmodle.ab");
        foreach (string name in strs)
        {
            //print(name);
            string path4 = @"http://192.168.215.117/AssetBundles/DoWindows/" + name;
            request2 = UnityWebRequestAssetBundle.GetAssetBundle(path4);
            yield return request2.SendWebRequest();
            AssetBundle ab2 = DownloadHandlerAssetBundle.GetContent(request2);

            //AssetBundle.LoadFromFile("AssetBundle/DoWindows/" + name);

        }
        GameObject go = Instantiate(obj, GameObject.Find("Canvas").transform);
        go.transform.localPosition = Vector3.zero;

        GameObject.Find("RegisterButton").GetComponent<Button>().onClick.AddListener(aaa);
        GameObject.Find("LoginButton").GetComponent<Button>().onClick.AddListener(bbb);
    }

    public void aaa()
    {
        string zhanghao = GameObject.Find("AccountInputField").GetComponent<InputField>().text;
        string mima = GameObject.Find("PassWordtInputField (1)").GetComponent<InputField>().text;
        PlayerPrefs.SetString("zhanghao", zhanghao);
        PlayerPrefs.SetString("mima", mima);
        print(PlayerPrefs.GetString("zhanghao", "aa"));
        print(PlayerPrefs.GetString("mima", "bb"));
    }

    public void bbb()
    {
        string dengluzhanghao = GameObject.Find("AccountInputField").GetComponent<InputField>().text;
        string denglumima= GameObject.Find("PassWordtInputField (1)").GetComponent<InputField>().text;
        if (dengluzhanghao== PlayerPrefs.GetString("zhanghao", "aa") &&denglumima== PlayerPrefs.GetString("mima", "bb"))
        {
            print("登陆成功");
        }
        else
        {
            print("登陆失败");
        }
    }
    //卸载资源  释放AssetBundle本身内存
    public void  UnLoad(AssetBundle ab)
    {
        if (ab==null)
        {
            return;
        }
        //卸载完ab包就不能用了,要置空
        ab.Unload(false);
    }

以上就是打AB包的流程以及最常用的几种加载AB包的方法,代码可以直接用,但是需要更改里面的细节。多用就会熟练

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值