AssetBundle

AssetBundle

1.打包

将要打包的资源在inspector中的预览窗口下设置要打包在AssetBundles下的路径和后缀名(可任意取)。新建一个C#脚本,脚本内容如下:

using System.IO;
using UnityEditor;

public class CreateAssetBundles 
{
    [MenuItem("Assets/Build AssetBundles")]//生成菜单目录
    static void BuildAllAssetBundles()
    {
        string assetBundleDirectory = "Assets/AssetBundles";//指定AssetBundles文件夹的目录
        if (!Directory.Exists(assetBundleDirectory))
        {
            Directory.CreateDirectory(assetBundleDirectory);//如果没有,则创建文件夹
        }
        BuildPipeline.BuildAssetBundles(assetBundleDirectory, BuildAssetBundleOptions.None,BuildTarget.StandaloneWindows);
    }
}
脚本无需挂载,在菜单Assets下点击新创建的Build AssetBundles,即可在指定文件夹创建AssetBundle.

2.读取

场景中物体上挂载一个脚本,脚本代码如下:

using UnityEngine;

public class LoadAssetBundle : MonoBehaviour
{
    void Start()
    {
        AssetBundle bundle = AssetBundle.LoadFromFile("Assets/AssetBundles/this/wall.ab");//找到AB包
        GameObject cubeWall = bundle.LoadAsset<GameObject>("CubeWall");//找到AB包中的物体
        Instantiate(cubeWall);//实例化物体
    }
}  

 运行后即可实例化物体。

posted @ 2023-03-11 15:04  gatran  阅读(24)  评论(0编辑  收藏  举报