Unity / C#
Intermediate
Unity 2021.3+ / Unity 6
Addressable 에셋 번들 비동기 로딩 및 메모리 누수 없는 릴리즈(Release) 패턴Addressable AssetBundle Asynchronous Loading and Leak-Free Release Pattern
Resources 폴더의 메모리 낭비를 제거하고 원격/로컬 에셋을 비동기로 로드하며 참조 카운팅(Reference Counting) 기반으로 안전하게 언로드하는 실무 패턴.Eliminating Resources folder memory overhead by loading remote and local assets asynchronously and unloading them safely using reference counting.
#Unity #Addressables #AssetBundle #Memory #Optimization
핵심 개념
Resources.Load는 빌드 시 앱의 시작 시간과 메모리 사용량을 증가시킵니다. Addressables 시스템은 에셋 주소(Key) 기반으로 메모리에 비동기 적재(LoadAssetAsync)하며, 더 이상 필요 없을 때 Addressables.Release로 핸들을 해제하여 안전한 메모리 해제를 수행합니다.Core Concept
Resources.Load increases application startup time and memory usage in builds. The Addressables system loads assets asynchronously by address key (LoadAssetAsync) and releases handles via Addressables.Release when no longer needed to perform safe memory deallocation.1. Addressables 안전 로드/언로드 래퍼1. Addressables Safe Load/Unload Wrapper
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;
public class AddressableLoader : MonoBehaviour
{
private AsyncOperationHandle<GameObject> _handle;
public async Task<GameObject> LoadPrefabAsync(string address)
{
_handle = Addressables.LoadAssetAsync<GameObject>(address);
await _handle.Task;
if (_handle.Status == AsyncOperationStatus.Succeeded)
{
return Instantiate(_handle.Result);
}
Debug.LogError($"[Addressables] 로드 실패: {address}");
return null;
}
private void OnDestroy()
{
// 핸들이 유효하면 메모리에서 언로드
if (_handle.IsValid())
{
Addressables.Release(_handle);
}
}
}
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;
public class AddressableLoader : MonoBehaviour
{
private AsyncOperationHandle<GameObject> _handle;
public async Task<GameObject> LoadPrefabAsync(string address)
{
_handle = Addressables.LoadAssetAsync<GameObject>(address);
await _handle.Task;
if (_handle.Status == AsyncOperationStatus.Succeeded)
{
return Instantiate(_handle.Result);
}
Debug.LogError($"[Addressables] Failed to load: {address}");
return null;
}
private void OnDestroy()
{
// Unload from memory if the handle is valid
if (_handle.IsValid())
{
Addressables.Release(_handle);
}
}
}
2. 실무 적용 및 주의사항2. Practical Application and Precautions
- 참조 카운트(Reference Count) 대칭 유지:
LoadAssetAsync호출 횟수만큼 정확히Addressables.Release가 호출되어야 실제 에셋 번들 메모리가 해제됩니다. InstantiateAsync와ReleaseInstance구분:Addressables.InstantiateAsync로 생성한 오브젝트는 일반Destroy대신 반드시Addressables.ReleaseInstance를 통해 파괴해야 참조 카운트가 정상 차감됩니다.- Event Viewer 프로파일링: 에디터의
Window > Asset Management > Addressables > Event Viewer를 활성화하면 런타임 중 에셋 적재 및 해제 시점을 실시간으로 추적할 수 있습니다.
- Maintain Reference Count Symmetry:
Addressables.Releasemust be called the exact same number of times asLoadAssetAsyncfor the underlying asset memory to be unloaded. - Distinguish
InstantiateAsyncandReleaseInstance: Objects created viaAddressables.InstantiateAsyncmust be destroyed usingAddressables.ReleaseInstancerather thanObject.Destroyto decrement the reference count properly. - Profile with Event Viewer: Enable
Window > Asset Management > Addressables > Event Viewerin the Editor to monitor asset load and release lifecycles at runtime.
컴포넌트 생명주기에 맞춰 비동기 로드 핸들을 보관하고 해제하는 규칙을 일관되게 적용하면, 대규모 씬 전환 환경에서도 메모리 누수를 예방할 수 있습니다.
Consistently storing and releasing asynchronous operation handles alongside component lifecycles prevents memory leaks across frequent scene transitions.