Asset bundles help you organize and load game assets efficiently. They make your game faster and smaller by loading only what you need.
Asset bundles and optimization in Unity
BuildPipeline.BuildAssetBundles(outputPath, BuildAssetBundleOptions.None, BuildTarget.StandaloneWindows64); // Load asset bundle AssetBundle bundle = AssetBundle.LoadFromFile(bundlePath); GameObject prefab = bundle.LoadAsset<GameObject>("MyPrefab"); Instantiate(prefab);
Use BuildPipeline.BuildAssetBundles to create asset bundles in the editor.
Load asset bundles at runtime with AssetBundle.LoadFromFile and then load assets inside them.
// Build asset bundles BuildPipeline.BuildAssetBundles("Assets/AssetBundles", BuildAssetBundleOptions.None, BuildTarget.StandaloneWindows64);
// Load asset bundle and instantiate prefab AssetBundle bundle = AssetBundle.LoadFromFile(Application.streamingAssetsPath + "/mybundle"); if (bundle != null) { GameObject prefab = bundle.LoadAsset<GameObject>("MyPrefab"); Instantiate(prefab); bundle.Unload(false); }
This script loads an asset bundle from the StreamingAssets folder, loads a prefab named "ExamplePrefab" from it, and creates it in the scene. It also logs success or failure messages.
using UnityEngine; public class LoadAssetBundleExample : MonoBehaviour { void Start() { string bundlePath = Application.streamingAssetsPath + "/examplebundle"; AssetBundle bundle = AssetBundle.LoadFromFile(bundlePath); if (bundle == null) { Debug.LogError("Failed to load AssetBundle!"); return; } GameObject prefab = bundle.LoadAsset<GameObject>("ExamplePrefab"); if (prefab != null) { Instantiate(prefab); Debug.Log("Prefab instantiated successfully."); } else { Debug.LogError("Prefab not found in bundle."); } bundle.Unload(false); } }
Always unload asset bundles after loading assets to free memory, using bundle.Unload(false).
Use asynchronous loading methods like AssetBundle.LoadFromFileAsync to avoid freezing the game during loading.
Organize assets into bundles carefully to avoid duplication and reduce download size.
Asset bundles let you load game assets only when needed, saving memory and download size.
Build asset bundles in the editor and load them at runtime with simple API calls.
Unload bundles after use and consider async loading for smooth gameplay.