微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Unity之AssetBundles基础

一 ,  准备制作一个AB包(以预制体为例)

        a, 制作1个胶囊体预制体

          b, 设置预制体CapsuleAB为AB包

               1, 进入CapsuleAB的"Inspector"面板

               2, 设置AssetBundle如下所示

 

        ①, ab/good    ,   ab为文件夹  good为生成AB文件名称

        ②, 后面的ab 可以理解为good文件的格式. 如下图所示:

 

二 , 制作AB包

1, 核心代码:

using System.IO;
using UnityEditor;
using UnityEngine;

public class CreateAssetBundles : MonoBehavIoUr
{
    [MenuItem("AlexHu/Build AssetBundles")]
    static void BuildAllAssetBundles()
    {
        string assetBundleDirectory = "AssetBundles";
        if(!Directory.Exists(assetBundleDirectory))
        {
            Directory.CreateDirectory(assetBundleDirectory);
        }
        BuildPipeline.BuildAssetBundles(assetBundleDirectory, 
                                        BuildAssetBundleOptions.None, 
                                        BuildTarget.StandaloneWindows);
    }
}

注解:

①, assetBundleDirectory : 将生成的AB资源放在项目更目录下(并非Assets目录下) , 如上面的ab/good , 就是在assetBundleDirectory 下生成一个ab文件夹, 将good放在ab文件夹中

②, 要将 CreateAssetBundles 放在Assets/Editor文件夹下.

③, 这样 Unity IDE上会出现AlexHu的菜单, 操作 AlexHu -> Build AssetBundles 就可以生成AB包了

 

三 , 使用AB资源(本次使用本地加载方式:AssetBundle.LoadFromFile为例)

代码如下:

using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
/// <summary>
/// 简单的AB,从本地加载
/// </summary>
public class ABSimpleDemo : MonoBehavIoUr
{
    private void Start()
    {
        AssetBundle ab = AssetBundle.LoadFromFile("AssetBundles/ab/good.ab");
        GameObject go = ab.LoadAsset<GameObject>("CapsuleAB");
        GameObject prefab =  Instantiate(go);
        prefab.transform.parent = this.transform;
    }
}

 

scene: 

 

四, 结果

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐