unity game, addressable resources loader.
I want MonoBehavior that lets me select addressable asset of specific type,
and it provides a method LoadResource() which loads addressable access and replaces specified Transform object, copying position, rotation and scale. I should be able to select moment when to run LoadResource(), start or manually.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Below is a compact “drop-in” MonoBehaviour that does exactly what you asked for:
• lets you pick an Addressable of a given type in the Inspector
• exposes LoadResource() so you can trigger the swap whenever you want
• optionally runs automatically on Start
• instantiates the loaded object, snaps it to the placeholder’s position / rotation / scale, and (optionally) kills the placeholder
• tracks the handle so the asset is released correctly when the component is destroyed
csharp
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;
/// <summary>
/// Replaces a placeholder Transform with an Addressable asset at runtime,
/// copying position / rotation / scale. Works with any prefab-like asset
/// (AssetReferenceGameObject). Release is handled automatically.
/// </summary>
public class AddressableResourceLoader : MonoBehaviour
{
public enum LoadMoment { OnStart, Manual }
[Header("Addressable to Spawn")]
[SerializeField] private AssetReferenceGameObject _asset; // drag any prefab addressable here
[Header("What to Replace")]
[SerializeField] private Transform _placeholder; // usually `this.transform`
[Header("Behaviour")]
[SerializeField] private LoadMoment _loadMoment = LoadMoment.OnStart;
[SerializeField] private bool _destroyPlaceholder = true;
// ————————————————————————————————————————————————————————————————
private AsyncOperationHandle<GameObject>? _handle; // track for Release()
private GameObject _spawnedInstance;
// Auto-trigger?
private async void Start()
{
if (_loadMoment == LoadMoment.OnStart)
await LoadResource();
}
/// <summary>
/// Public entry point – call from code / button / timeline / etc.
/// Returns the instance it spawned (null if failed).
/// </summary>
public async Task<GameObject> LoadResource()
{
if (_asset == null)
{
Debug.LogWarning("AddressableResourceLoader: no asset set.", this);
return null;
}
// Already loaded? Just return the existing instance.
if (_spawnedInstance != null) return _spawnedInstance;
// 1) Spawn the prefab asynchronously.
_handle = Addressables.InstantiateAsync(
_asset,
_placeholder.position,
_placeholder.rotation,
_placeholder.parent); // keep same parent
await _handle.Value.Task;
if (!_handle.Value.IsValid() || _handle.Value.Status != AsyncOperationStatus.Succeeded)
{
Debug.LogError($"Failed to load {_asset.RuntimeKey}", this);
return null;
}
_spawnedInstance = _handle.Value.Result;
// 2) Copy scale (InstantiateAsync copied pos/rot already).
_spawnedInstance.transform.localScale = _placeholder.localScale;
// 3) Optionally destroy/disable placeholder.
if (_destroyPlaceholder && _placeholder != null)
Destroy(_placeholder.gameObject);
return _spawnedInstance;
}
// Clean up
private void OnDestroy()
{
if (_handle.HasValue)
Addressables.ReleaseInstance(_handle.Value); // also releases the asset
}
}
How to use
Make sure Addressables are enabled in your project (Window ▶ Asset Management ▶ Addressables).
Put the script on any GameObject in your scene (e.g., a dummy cube that represents the object you’ll swap).
In the Inspector:
• “Asset” – drag an Addressable prefab (thanks to AssetReferenceGameObject, only prefabs appear).
• “Placeholder” – drag the Transform you want to replace (often just “Self”).
• Choose “OnStart” or “Manual”.
public class ExampleCaller : MonoBehaviour
{
[SerializeField] private AddressableResourceLoader loader;
public async void OnClick() => await loader.LoadResource();
}
Limiting to other asset types
Need a Sprite, AudioClip, Material, etc.?
Just make a tiny typed AssetReference subclass so the Inspector only shows that type:
csharp
using UnityEngine;
using UnityEngine.AddressableAssets;
[System.Serializable] public class AssetReferenceSprite : AssetReferenceT<Sprite> {
public AssetReferenceSprite(string guid) : base(guid) {}
}
In that case you’ll likely want to load with Addressables.LoadAssetAsync<Sprite> instead of InstantiateAsync, but the rest of the workflow is identical.
Enjoy streamlined Addressable swapping! 🎮
User
it should track resource loaded state avoiding double loads. it should allow unloading resource to free memory up. It should use UniTask, support useful loading event actions
Assistant
Here’s a beefed-up, UniTask-powered loader that
• avoids duplicate loading (re-uses the same task)
• exposes UnloadResource() to free RAM / GPU mem
• fires handy UnityEvents (Start, Progress, Done, Unload)
• works with UniTask’s async/await, so it plays nicely with DOTS, hot-reload, etc.
Copy–paste the script, then read the HOW-TO right below it.
csharp
/* AddressableResourceLoader.cs ──────────────────────────────────────────────
* – Select an Addressable prefab (AssetReferenceGameObject) in the Inspector
* – Call LoadResource() whenever you want (or let it auto-load on Start)
* – It instantiates the prefab, snaps to placeholder’s pos/rot/scale,
* tracks loading state, lets you unload, and broadcasts UnityEvents.
* – Uses UniTask (Cysharp.Threading.Tasks) instead of System.Threading.Tasks.
* ───────────────────────────────────────────────────────────────────────────*/
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;
using Cysharp.Threading.Tasks; // ★ UniTask ★
[AddComponentMenu("Addressables/Addressable Resource Loader")]
public class AddressableResourceLoader : MonoBehaviour
{
// ────────────────────────────────────────────────────────── Inspector ────
public enum LoadMoment { OnStart, Manual }
[Header("Addressable Prefab")]
[SerializeField] private AssetReferenceGameObject asset;
[Header("Placeholder (transform to mimic)")]
[SerializeField] private Transform placeholder; // default: self
[Header("Timing")]
[SerializeField] private LoadMoment loadMoment = LoadMoment.OnStart;
[Header("Behaviour")]
[SerializeField] private bool destroyPlaceholder = true;
[Header("Events")]
public UnityEvent onLoadStarted;
public UnityEvent<float> onLoadProgress; // 0…1
public UnityEvent<GameObject> onLoaded;
public UnityEvent onUnloaded;
// ─────────────────────────────────────────────────── internal state ────
private AsyncOperationHandle<GameObject> handle;
private GameObject instance;
private UniTask<GameObject> loadingTask; // reuse for dedup
private bool isLoading;
private bool isLoaded;
// ──────────────────────────────────────────────────────────── LIFECYCLE ─
private void Awake()
{
if (placeholder == null) placeholder = transform;
}
private async void Start()
{
if (loadMoment == LoadMoment.OnStart)
await LoadResource();
}
private void OnDestroy()
{
UnloadResource(); // auto-clean
}
// ────────────────────────────────────────────────────── PUBLIC API ─────
public async UniTask<GameObject> LoadResource()
{
if (isLoaded) return instance; // already done
if (isLoading) return await loadingTask; // someone else is loading
if (asset == null)
{
Debug.LogWarning("AddressableResourceLoader: Asset is null", this);
return null;
}
isLoading = true;
onLoadStarted?.Invoke();
// Kick off the async instantiate & convert to UniTask with progress cb
handle = Addressables.InstantiateAsync(
asset,
placeholder.position,
placeholder.rotation,
placeholder.parent);
loadingTask = handle.ToUniTask(
progress: Progress.Create<float>(p => onLoadProgress?.Invoke(p)),
cancellationToken: this.GetCancellationTokenOnDestroy());
instance = await loadingTask;
isLoading = false;
isLoaded = true;
if (instance == null)
{
Debug.LogError($"Failed to instantiate {asset.RuntimeKey}", this);
return null;
}
// Copy scale (InstantiateAsync already matched pos/rot)
instance.transform.localScale = placeholder.localScale;
if (destroyPlaceholder && placeholder != null)
Destroy(placeholder.gameObject);
onLoaded?.Invoke(instance);
return instance;
}
public void UnloadResource()
{
if (!isLoaded) return;
Addressables.ReleaseInstance(handle);
isLoaded = false;
instance = null;
loadingTask = default;
onUnloaded?.Invoke();
}
// Convenience – returns true if prefab is in scene and valid
public bool IsLoaded => isLoaded && instance != null;
}
How to wire it up
Install UniTask (✱)
• Open Package Manager → + → Add package from Git URL
• https://github.com/Cysharp/UniTask.git
Enable Addressables (if not already)
Window → Asset Management → Addressables → Groups
Add the script to a placeholder object in your scene (usually an empty or a simple cube).
Drag an Addressable prefab into the “Asset” slot.
(Only prefabs appear because the field is AssetReferenceGameObject.)
Optionally hook up UnityEvents:
• Progress bar UI → OnLoadProgress(float)
• Something like play a VFX → OnLoaded
• Memory meter → OnUnloaded
Choose when it should load:
• OnStart – fires automatically in Start()
• Manual – call await loader.LoadResource(); or hook it to a UI Button.
API Cheatsheet
csharp
public AddressableResourceLoader loader;
// async/await usage
await loader.LoadResource();
// unload later; frees RAM/GPU
loader.UnloadResource();
// status flags
if (loader.IsLoaded) ...
UniTask notes
• LoadResource() returns UniTask<GameObject>; you can await it or use .Forget() if you don’t care about the result.
• The progress callback sends a float 0‒1 to onLoadProgress, letting you drive sliders or text.
• We pass GetCancellationTokenOnDestroy() so the task cancels automatically if the GameObject is removed (scene unload, play-mode stop, etc.).