How to create and use AssetBundles in Unity
Using AssetBundles is a great way to reduce the size of your application by making it possible to stream the assets outside of the main application, either locally on device or from the web. Let’s go over how to use AssetBundles.
For this article I am streaming from the web using AWS S3 storage. You will not need the AWS SDK for this to work. All you need is a bucket for storing the files and I have shown in this article how to create a bucket.
First, to be able to create an AssetBundle we need to add the option to the Editor. Create a folder called Editor and create a script inside this folder called CreateAssetBundles:
Open up the script and replace the code in the script with the code below. This will add an option to the Assets menu called Build AssetBundles and when used it will create the AssetBundle inside the folder StreamingAssets. An AssetBundle is target specific so in this example the bundle is built for Android:
In the Editor select the files you want to add to an AssetBundle and set the name of the bundle it should belong to:
Open to the Asset menu and select the new option Build AssetBundles. The AssetBundles will then show up under the folder StreamingAssets:
Login on AWS and upload the file to the bucket and ensure that public access is set to read:
Click on the file and make a note of the URL:
Create a game object called AssetLoader and attach a new script with the same name to this object:
Open up the AssetLoader script. In this example the AssetBundle will get retrieved from the Start function. The function the asset is retrieved from must be of return type IEnumerator. Once the AssetBundle has been retrieved you can get the specific asset by name and instantiate it in the scene: