Working synchronous Addressables settings loading

This commit is contained in:
Michal Pikulski
2025-09-23 15:30:21 +02:00
parent 197aedddb0
commit 404f6f4e5c
4 changed files with 97 additions and 75 deletions

View File

@@ -8,6 +8,7 @@ namespace AppleHills.Core.Settings
{
/// <summary>
/// Responsible for loading and caching settings from Addressables.
/// Uses synchronous loading to ensure settings are available immediately.
/// </summary>
public class SettingsProvider : MonoBehaviour
{
@@ -43,64 +44,57 @@ namespace AppleHills.Core.Settings
}
/// <summary>
/// Load settings asynchronously using Addressables
/// Load settings synchronously using Addressables - blocks until complete
/// </summary>
public void LoadSettings<T>(Action<T> onLoaded) where T : BaseSettings
public T LoadSettingsSynchronous<T>() where T : BaseSettings
{
string key = typeof(T).Name;
// Return from cache if already loaded
if (_settingsCache.TryGetValue(key, out BaseSettings cachedSettings))
{
onLoaded?.Invoke(cachedSettings as T);
return;
return cachedSettings as T;
}
// Load using Addressables
Addressables.LoadAssetAsync<T>($"Settings/{key}.asset").Completed += handle =>
// Load using Addressables synchronously
try
{
if (handle.Status == AsyncOperationStatus.Succeeded)
// WaitForCompletion blocks until the asset is loaded
T settings = Addressables.LoadAssetAsync<T>($"Settings/{key}").WaitForCompletion();
if (settings != null)
{
_settingsCache[key] = handle.Result;
onLoaded?.Invoke(handle.Result);
_settingsCache[key] = settings;
return settings;
}
else
{
Debug.LogError($"Failed to load settings: {key}");
onLoaded?.Invoke(null);
}
};
}
/// <summary>
/// Get cached settings
/// </summary>
public T GetSettings<T>() where T : BaseSettings
{
string key = typeof(T).Name;
if (_settingsCache.TryGetValue(key, out BaseSettings settings))
{
return settings as T;
}
catch (Exception e)
{
Debug.LogError($"Error loading settings {key}: {e.Message}");
}
return null;
}
/// <summary>
/// Preload all settings - call this at game startup
/// Get cached settings or load them synchronously if not cached
/// </summary>
public void PreloadAllSettings(Action onComplete)
public T GetSettings<T>() where T : BaseSettings
{
// Load all necessary settings types
int pendingLoads = 3; // Number of settings types
Action decrementCounter = () => {
pendingLoads--;
if (pendingLoads <= 0)
onComplete?.Invoke();
};
string key = typeof(T).Name;
LoadSettings<PlayerFollowerSettings>(settings => decrementCounter());
LoadSettings<InteractionSettings>(settings => decrementCounter());
LoadSettings<MinigameSettings>(settings => decrementCounter());
// Return from cache if already loaded
if (_settingsCache.TryGetValue(key, out BaseSettings cachedSettings))
{
return cachedSettings as T;
}
// Load synchronously if not in cache
return LoadSettingsSynchronous<T>();
}
}
}