ProjectDDD/Assets/_DDD/_Scripts/AssetManagement/AssetManager.cs

100 lines
2.8 KiB
C#
Raw Normal View History

2025-07-10 05:48:44 +00:00
using System;
using System.Linq;
using System.Threading.Tasks;
2025-07-15 03:59:53 +00:00
#if UNITY_EDITOR
using UnityEditor.AddressableAssets;
2025-07-15 03:59:53 +00:00
#endif
2025-07-09 09:45:11 +00:00
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;
using UnityEngine.ResourceManagement.ResourceProviders;
using UnityEngine.SceneManagement;
2025-07-09 09:45:11 +00:00
namespace DDD
{
public class AssetManager : Singleton<AssetManager>, IManager
{
public void Init()
{
}
2025-07-10 05:48:44 +00:00
public async void PostInit()
2025-07-09 09:45:11 +00:00
{
2025-07-10 05:48:44 +00:00
try
{
await Addressables.InitializeAsync().Task;
}
catch (Exception e)
{
Debug.Assert(false, $"Addressables initialization failed\n{e}");
2025-07-10 05:48:44 +00:00
}
}
public static async Task<T> LoadAsset<T>(string key) where T : UnityEngine.Object
2025-07-10 05:48:44 +00:00
{
var handle = Addressables.LoadAssetAsync<T>(key);
await handle.Task;
2025-07-10 05:48:44 +00:00
if (handle.Status == AsyncOperationStatus.Succeeded)
return handle.Result;
Debug.LogError($"Addressable load failed : {key}");
return null;
2025-07-09 09:45:11 +00:00
}
public static async Task<T> LoadAsset<T>(AssetReference reference) where T : UnityEngine.Object
{
if (reference == null)
{
Debug.LogError("Null AssetReference");
return null;
}
var handle = reference.LoadAssetAsync<T>();
await handle.Task;
if (handle.Status == AsyncOperationStatus.Succeeded)
return handle.Result;
Debug.LogError($"AssetReference load failed: {reference.RuntimeKey}");
return null;
}
public static async Task<SceneInstance> LoadScene(string key, LoadSceneMode mode = LoadSceneMode.Additive)
{
var handle = Addressables.LoadSceneAsync(key, mode);
await handle.Task;
if (handle.Status == AsyncOperationStatus.Succeeded)
return handle.Result;
Debug.LogError($"Scene load failed: {key}");
return default;
}
public static async Task UnloadScene(SceneInstance sceneInstance)
{
var handle = Addressables.UnloadSceneAsync(sceneInstance);
await handle.Task;
}
public static bool HasLabel(string addressKey, string label)
{
#if UNITY_EDITOR
var settings = AddressableAssetSettingsDefaultObject.Settings;
if (settings == null) return false;
var entry = settings.groups
.SelectMany(g => g.entries)
.FirstOrDefault(e => e.address == addressKey);
if (entry == null) return false;
return entry.labels.Contains(label);
#else
return true;
#endif
}
2025-07-09 09:45:11 +00:00
}
}