docs.unity3d.com
Search Results for

    Show / Hide Table of Contents

    Load an AssetReference

    The AssetReference class has its own load method, LoadAssetAsync:

    
    using UnityEngine;
    using UnityEngine.AddressableAssets;
    using UnityEngine.ResourceManagement.AsyncOperations;
    
    internal class LoadFromReference : MonoBehaviour
    {
        // Assign in Editor
        public AssetReference reference;
    
        // Start the load operation on start
        void Start()
        {
            AsyncOperationHandle handle = reference.LoadAssetAsync<GameObject>();
            handle.Completed += Handle_Completed;
        }
    
        // Instantiate the loaded prefab on complete
        private void Handle_Completed(AsyncOperationHandle obj)
        {
            if (obj.Status == AsyncOperationStatus.Succeeded)
            {
                Instantiate(reference.Asset, transform);
            }
            else
            {
                Debug.LogError("AssetReference failed to load.");
            }
        }
    
        // Release asset when parent object is destroyed
        private void OnDestroy()
        {
            reference.ReleaseAsset();
        }
    }
    
    

    You can also use the AssetReference object as a key to the Addressables.LoadAssetAsync methods. If you need to spawn multiple instances of the asset assigned to an AssetReference, use Addressables.LoadAssetAsync, which gives you an operation handle that you can use to release each instance.

    In This Article
    Back to top
    Copyright © 2024 Unity Technologies — Trademarks and terms of use
    • Legal
    • Privacy Policy
    • Cookie Policy
    • Do Not Sell or Share My Personal Information
    • Your Privacy Choices (Cookie Settings)