Skip to content

Instantly share code, notes, and snippets.

@baba-s
Created June 8, 2021 12:27
Show Gist options
  • Save baba-s/50695b99a74140d9ff8d53a6a0091561 to your computer and use it in GitHub Desktop.
Save baba-s/50695b99a74140d9ff8d53a6a0091561 to your computer and use it in GitHub Desktop.
using System.Linq;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;
using UnityEngine.ResourceManagement.ResourceLocations;
using UnityEngine.ResourceManagement.ResourceProviders;
public sealed class AddressablesDownloader
{
public int DownloadedCount { get; private set; }
public int TotalCount { get; private set; }
public float Progress => ( float ) DownloadedCount / TotalCount;
public async Task<bool> DownloadAsync( string label )
{
if ( !Addressables.Instance.GetResourceLocations( label, typeof( object ), out var locations ) )
{
return false;
}
var isFailure = false;
var dependencies = AddressablesImpl.GatherDependenciesFromLocations( locations );
bool IsCached( IResourceLocation location )
{
var options = ( AssetBundleRequestOptions ) location.Data;
var cachedBundle = new CachedAssetBundle
(
name: options.BundleName,
hash: Hash128.Parse( options.Hash )
);
return Caching.IsVersionCached( cachedBundle );
}
async Task LoadAsset( IResourceLocation location )
{
if ( isFailure ) return;
var handle = Addressables.LoadAssetAsync<IAssetBundleResource>( location );
await handle.Task;
if ( handle.Status == AsyncOperationStatus.Succeeded )
{
DownloadedCount++;
}
else
{
isFailure = true;
}
Addressables.Release( handle );
}
var tasks = dependencies
.Where( x => !IsCached( x ) )
.Select( x => LoadAsset( x ) )
.ToArray()
;
DownloadedCount = 0;
TotalCount = tasks.Length;
await Task.WhenAll( tasks );
return !isFailure;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment