欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Unity AssetBundle 打包小记

程序员文章站 2022-04-03 15:57:13
...

1.命名

Unity AssetBundle 打包小记

命名注意:sky表示生成的目录 sky01 是ab包的名字。  ab是生成文件的后缀名

2.打包脚本

 [MenuItem("ThrusdayFrame/Build AssetBundle")]
    public static void BuildBundle()
    {
        string dir = "AssetBundles";
        if (Directory.Exists(dir) == false)
        {
            Directory.CreateDirectory(dir);
        }
        //BuildTarget 选择build出来的AB包要使用的平台
        BuildPipeline.BuildAssetBundles(dir, BuildAssetBundleOptions.None, BuildTarget.StandaloneWindows);
    }

3.加载脚本,以网络地址下载天空和材质球更换为例。

 IEnumerator DoChangeOnLine(string key)
    {
        //网络地址
        string str = "http://192.168.1.121/AssetBundles/sky/sky" + key + ".ab";
        //下载
        UnityWebRequest wb = UnityWebRequestAssetBundle.GetAssetBundle(str);
        yield return wb.SendWebRequest();
        //获取
        AssetBundle assetBundle = DownloadHandlerAssetBundle.GetContent(wb);
        if (wb.isDone)
        {
            Debug.Log(wb.error);

            temp = RenderSettings.skybox.GetFloat("_Exposure");
            while (temp > 0.01f)
            {
                temp -= Time.deltaTime * changeSpeed;
                temp = Mathf.Clamp(temp, 0, 1);
                RenderSettings.skybox.SetFloat("_Exposure", temp);
                yield return null;
            }
           //替换
            RenderSettings.skybox = assetBundle.LoadAssetAsync<Material>("Mat_" + key).asset as Material;

            blackToDo?.Invoke();

            RenderSettings.skybox.SetFloat("_Exposure", 0);
            temp = RenderSettings.skybox.GetFloat("_Exposure");
            while (temp < 0.99f)
            {
                temp += Time.deltaTime * changeSpeed;
                temp = Mathf.Clamp(temp, 0, 1);
                RenderSettings.skybox.SetFloat("_Exposure", temp);
                yield return null;
            }

        }
        yield return null;

    }