Version: 2022.3
LanguageEnglish
  • C#

BuildPipeline.BuildAssetBundles

Suggest a change

Success!

Thank you for helping us improve the quality of Unity Documentation. Although we cannot accept all submissions, we do read each suggested change from our users and will make updates where applicable.

Close

Submission failed

For some reason your suggested change could not be submitted. Please <a>try again</a> in a few minutes. And thank you for taking the time to help us improve the quality of Unity Documentation.

Close

Cancel

Declaration

public static AssetBundleManifest BuildAssetBundles(BuildAssetBundlesParameters buildParameters);

Parameters

buildOptions Configuration of the build.

Returns

AssetBundleManifest The manifest summarizing all AssetBundles generated by the build.

Description

Build AssetBundles.

This signature of BuildAssetBundles is recommended and exposes the most functionality. The other signatures, documented below, are retained for backward compatibility and convenience.

During the AssetBundle build process, classes that implement IProcessSceneWithReport will be called as Scenes are processed. Similarly the way Shaders are built can be influenced by implementing IPreprocessShaders or IPreprocessComputeShaders.

This function returns an AssetBundleManifest instance that describes the bundles produced. If the build fails then the function returns null or throws an exception. You can find details about what went wrong in the exception message or in errors logged to the console. For example, if you pass an invalid or non-existent path as the outputPath parameter, the function throws an ArgumentException to indicate that the supplied argument was invalid.

Additional resources: Building AssetBundles

using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEngine;
using UnityEditor;
public class BuildAssetBundlesExample
{
    [MenuItem("Example/Build AssetBundles")]
    static void BuildBundles()
    {
        List<AssetBundleBuild> assetBundleDefinitionList = new();
        // Define two asset bundles, populated based on file system structure
        // The first bundle is all the scene files in the Scenes directory (non-recursive)
        {
            AssetBundleBuild ab = new();
            ab.assetBundleName = "Scenes";
            ab.assetNames = Directory.EnumerateFiles("Assets/" + ab.assetBundleName, "*.unity", SearchOption.TopDirectoryOnly).ToArray();
            assetBundleDefinitionList.Add(ab);
        }
        // The second bundle is all the asset files found recursively in the Meshes directory
        {
            AssetBundleBuild ab = new();
            ab.assetBundleName = "Meshes";
            ab.assetNames = RecursiveGetAllAssetsInDirectory("Assets/" + ab.assetBundleName).ToArray();
            assetBundleDefinitionList.Add(ab);
        }
        string outputPath = "MyBuild";  // Subfolder of the current project
        if (!Directory.Exists(outputPath))
            Directory.CreateDirectory(outputPath);
        // Assemble all the input needed to perform the build in this structure.
        // The project's current build settings will be used because target and subtarget fields are not filled in
        BuildAssetBundlesParameters buildInput = new()
        {
            outputPath = outputPath,
            options = BuildAssetBundleOptions.AssetBundleStripUnityVersion,
            bundleDefinitions = assetBundleDefinitionList.ToArray()
        };
        AssetBundleManifest manifest = BuildPipeline.BuildAssetBundles(buildInput);
        // Look at the results
        if (manifest != null)
        {
            foreach(var bundleName in manifest.GetAllAssetBundles())
            {
                string projectRelativePath = buildInput.outputPath + "/" + bundleName;
                Debug.Log($"Size of AssetBundle {projectRelativePath} is {new FileInfo(projectRelativePath).Length}");
            }
        }
        else
        {
            Debug.Log("Build failed, see Console and Editor log for details");
        }
    }
    static List<string> RecursiveGetAllAssetsInDirectory(string path)
    {
        List<string> assets = new();
        foreach (var f in Directory.EnumerateFiles(path, "*", SearchOption.AllDirectories))
            if (Path.GetExtension(f) != ".meta" &&
                Path.GetExtension(f) != ".cs" &&  // Scripts are not supported in AssetBundles
                Path.GetExtension(f) != ".unity") // Scenes cannot be mixed with other file types in a bundle
                assets.Add(f);
        return assets;
    }
}

In addition to the AssetBundle files, the build will produce several other files:

* The AssetBundleManifest is stored in a small AssetBundle that has the same name as the output folder, for example "MyBundleFolder". This is the same object that is returned from the BuildAssetBundles call, and the serialized form can be useful at runtime, for example to determine the expected hashes of the other AssetBundles.

* The main ".manifest" file, which is a text format file. It has the same name as the output folder, but using ".manifest" as its extension (for example: "MyBundleFolder.manifest"). Assign the path to this manifest file to BuildPlayerOptions.assetBundleManifestPath before calling BuildPipeline.BuildPlayer to make sure that any types appearing in the AssetBundles are not stripped from the build. (See Managed code stripping for more information about code stripping.)

* There is also a separate ".manifest" file written for each AssetBundle, based on the name of the AssetBundle.

* Finally, the BuildReport for the build is written to "Library/LastBuild.buildreport".

using System.IO;
using UnityEngine;
using UnityEditor;
public class BuildAssetBundlesOutputFileExample
{
    [MenuItem("Example/AssetBundle Output File Example")]
    static void BuildAndPrintOutputFiles()
    {
        var bundleDefinitions = new AssetBundleBuild[]
        {
            new AssetBundleBuild
            {
                assetBundleName = "mybundle",
                assetNames = new string[] { "Assets/Scenes/Scene1.unity" }
            }
        };
        string buildOutputDirectory = "build";
        Directory.CreateDirectory(buildOutputDirectory);
        BuildAssetBundlesParameters buildInput = new()
        {
            outputPath = buildOutputDirectory,
            bundleDefinitions = bundleDefinitions
        };
        AssetBundleManifest manifest = BuildPipeline.BuildAssetBundles(buildInput);
        if (manifest != null)
        {
            var outputFiles = Directory.EnumerateFiles(buildOutputDirectory, "*", SearchOption.TopDirectoryOnly);
            //Expected output (on Windows):
            //  Output of the build:
            //      build\build
            //      build\build.manifest
            //      build\mybundle
            //      build\mybundle.manifest
            Debug.Log("Output of the build:\n\t" + string.Join("\n\t", outputFiles));
        }
    }
}

Declaration

public static AssetBundleManifest BuildAssetBundles(string outputPath, BuildAssetBundleOptions assetBundleOptions, BuildTarget targetPlatform);

Parameters

outputPath Output path for the AssetBundles.
assetBundleOptions AssetBundle building options.
targetPlatform Chosen target build platform.

Returns

AssetBundleManifest The manifest listing all AssetBundles included in this build.

Description

Build all AssetBundles.

Use this function to build AssetBundles based on the AssetBundle and Label settings you have configured in the Editor. (See the Manual page about building AssetBundles for further details.)

Set outputPath to the folder within your project folder where you want to save the built bundles (for example: "Assets/MyBundleFolder"). The folder is not created automatically and the function simply fails if it doesn't already exist. The files created by this function include a manifest file, with the same name as the output folder, but using ".manifest" as its extension (for example: "MyBundleFolder.manifest"). Assign the path to this manifest file to BuildPlayerOptions.assetBundleManifestPath before calling BuildPipeline.BuildPlayer to make sure that any types appearing in the AssetBundles are not stripped from the build. (See Managed code stripping for more information about code stripping.)

Use the optional assetBundleOptions argument to specify bundle build options.

The targetPlatform argument selects which deployment target (Windows Standalone, Android, iOS, and so on) to build the bundles for. An AssetBundle is only compatible with the specific platform that it was built for, so you must produce different builds of a given bundle to use the assets on different platforms. See EditorUserBuildSettings.activeBuildTarget and the BuildTarget section of the Building AssetBundles page in the Manual for more information about creating AssetBundles for different platforms.

During the AssetBundle build process, classes that implement IProcessSceneWithReport will be called as Scenes are processed. Similarly the way Shaders are built can be influenced by implementing IPreprocessShaders or IPreprocessComputeShaders.

This function returns an AssetBundleManifest instance that describes the bundles produced. If the build fails then the function returns null or throws an exception. You can find details about what went wrong in the exception message or in errors logged to the console. For example, if you pass an invalid or non-existent path as the outputPath parameter, the function throws an ArgumentException to indicate that one of the supplied arguments was invalid

Additional resources: EditorUserBuildSettings.activeBuildTarget, AssetDatabase.GetAssetPathsFromAssetBundle, AssetDatabase.GetImplicitAssetBundleName, AssetImporter.assetBundleName, AssetBundle

// Create an AssetBundle for Windows.
using UnityEngine;
using UnityEditor;

public class BuildAssetBundlesExample { [MenuItem("Example/Build Asset Bundles")] static void BuildABs() { // Put the bundles in a folder called "ABs" within the Assets folder. BuildPipeline.BuildAssetBundles("Assets/ABs", BuildAssetBundleOptions.None, BuildTarget.StandaloneWindows); } }

Declaration

public static AssetBundleManifest BuildAssetBundles(string outputPath, AssetBundleBuild[] builds, BuildAssetBundleOptions assetBundleOptions, BuildTarget targetPlatform);

Parameters

outputPath Output path for the AssetBundles.
builds AssetBundle building map.
assetBundleOptions AssetBundle building options.
targetPlatform Target build platform.

Returns

AssetBundleManifest The manifest listing all AssetBundles included in this build.

Description

Build AssetBundles from a building map.

This signature of BuildAssetBundles lets you specify the names and contents of the bundles programmatically, using a "build map" rather than with the details set in the editor. The map is simply an array of AssetBundleBuild objects, each of which contains a bundle name and a list of the names of asset files to be added to the named bundle.

using UnityEngine;
using UnityEditor;

public class BuildAssetBundlesBuildMapExample { [MenuItem("Example/Build Asset Bundles Using BuildMap")] static void BuildMapABs() { // Create the array of bundle build details. AssetBundleBuild[] buildMap = new AssetBundleBuild[2];

buildMap[0].assetBundleName = "enemybundle";

string[] enemyAssets = new string[2]; enemyAssets[0] = "Assets/Textures/char_enemy_alienShip.jpg"; enemyAssets[1] = "Assets/Textures/char_enemy_alienShip-damaged.jpg";

buildMap[0].assetNames = enemyAssets; buildMap[1].assetBundleName = "herobundle";

string[] heroAssets = new string[1]; heroAssets[0] = "char_hero_beanMan"; buildMap[1].assetNames = heroAssets;

BuildPipeline.BuildAssetBundles("Assets/ABs", buildMap, BuildAssetBundleOptions.None, BuildTarget.StandaloneWindows); } }