Here’s a simple Unity C# script to load an AssetBundle from Google Play Asset Delivery at runtime. This example assumes you have already set up Google Play Asset Delivery in your Unity project and uploaded asset bundles to Google Play Console.
Steps:
- Place this script in your Unity project.
- Ensure the asset bundle is marked as Play Asset Delivery in Unity’s Addressable Asset settings.
- Deploy your app on an Android device with Google Play support.
C# Code for Loading an AssetBundle at Runtime
This script demonstrates how to download an asset bundle and instantiate a prefab from it.
csharpCopyEditusing UnityEngine;
using Google.Play.AssetDelivery;
using System.Collections;
public class PlayAssetBundleLoader : MonoBehaviour
{
public string assetBundleName = "your_asset_bundle_name"; // Change this to your asset bundle name
public string assetName = "YourPrefab"; // Name of the asset inside the bundle
private AssetBundle assetBundle;
void Start()
{
StartCoroutine(DownloadAssetBundle());
}
IEnumerator DownloadAssetBundle()
{
// Request the asset bundle from Google Play Asset Delivery
var request = PlayAssetDelivery.RetrieveAssetBundleAsync(assetBundleName);
while (!request.IsDone)
{
Debug.Log($"Downloading: {request.DownloadProgress * 100}%");
yield return null;
}
if (request.Error != AssetDeliveryErrorCode.NoError)
{
Debug.LogError($"Failed to load asset bundle: {request.Error}");
yield break;
}
assetBundle = request.AssetBundle;
Debug.Log($"Successfully loaded asset bundle: {assetBundleName}");
LoadAssetFromBundle();
}
void LoadAssetFromBundle()
{
if (assetBundle == null)
{
Debug.LogError("AssetBundle is not loaded!");
return;
}
// Load the prefab from the asset bundle
GameObject prefab = assetBundle.LoadAsset<GameObject>(assetName);
if (prefab != null)
{
Instantiate(prefab);
Debug.Log($"Successfully instantiated {assetName}");
}
else
{
Debug.LogError($"Failed to load {assetName} from {assetBundleName}");
}
}
void OnDestroy()
{
if (assetBundle != null)
{
assetBundle.Unload(false);
}
}
}
How It Works:
- The script downloads the asset bundle using Google Play Asset Delivery.
- It waits for the bundle to be fully downloaded.
- Once downloaded, it loads a prefab from the asset bundle and instantiates it in the scene.
Notes:
- Ensure Google Play Asset Delivery is enabled in Unity’s AssetBundle settings.
- The asset bundle name should match the name set in Google Play Console.
- This code should run on a real Android device, not in the Unity Editor.