diff --git a/Assets/YooAsset/Runtime/OperationSystem/AsyncOperationBase.cs b/Assets/YooAsset/Runtime/OperationSystem/AsyncOperationBase.cs index debf5fa3..513a61ef 100644 --- a/Assets/YooAsset/Runtime/OperationSystem/AsyncOperationBase.cs +++ b/Assets/YooAsset/Runtime/OperationSystem/AsyncOperationBase.cs @@ -10,17 +10,22 @@ namespace YooAsset { private List _childs; private Action _callback; - private uint _priority = 0; + private uint _priority; /// /// 等待异步执行完成 /// - internal bool IsWaitForAsyncComplete { private set; get; } = false; + internal bool IsWaitForAsyncComplete { get; private set; } + + /// + /// 标记脏(用于调度器检测并重排) + /// + internal bool IsDirty { get; set; } /// /// 是否已经完成 /// - internal bool IsFinish { private set; get; } = false; + internal bool IsFinish { get; private set; } /// /// 异步系统是否繁忙 @@ -35,11 +40,6 @@ namespace YooAsset } } - /// - /// 标记脏(用于调度器检测并重排) - /// - internal bool IsDirty { set; get; } = false; - /// /// 任务优先级 /// @@ -98,6 +98,7 @@ namespace YooAsset { try { + //注意:任务已完成,立即调用回调 value.Invoke(this); } catch (Exception ex) @@ -295,21 +296,25 @@ namespace YooAsset // 结束记录 DebugEndRecording(); - try + if (_callback != null) { - //TODO 单个回调异常会阻断后续订阅者 - _callback?.Invoke(this); - } - catch (Exception ex) - { - YooLogger.Error($"Exception in completion callback: {ex}"); - } - finally - { - _callback = null; - if (_taskCompletionSource != null) - _taskCompletionSource.TrySetResult(null); + var invocationList = _callback.GetInvocationList(); + foreach (var handler in invocationList) + { + try + { + ((Action)handler).Invoke(this); + } + catch (Exception ex) + { + YooLogger.Error($"Exception in completion callback: {ex}"); + } + } } + + _callback = null; + if (_taskCompletionSource != null) + _taskCompletionSource.TrySetResult(null); } } @@ -327,7 +332,10 @@ namespace YooAsset /// /// 批量执行一定次数的更新逻辑 /// - /// 次数 + /// 最大执行次数,默认1000次 + /// + /// 用于需要快速完成但又不想完全阻塞主线程的场景。 + /// protected void RunBatchExecution(int count = 1000) { if (IsDone) @@ -374,7 +382,7 @@ namespace YooAsset /// public void WaitForAsyncComplete() { - //TODO 防止异步操作被挂起陷入无限死循环! + //注意:防止异步操作被挂起陷入无限死循环! if (Status == EOperationStatus.None) { StartOperation(); @@ -400,15 +408,17 @@ namespace YooAsset } #region 调试信息 + private const int MaxCycleCheckDepth = 4096; // 循环检测最大深度 + /// /// 开始的时间 /// - public string BeginTime { protected set; get; } + public string BeginTime { get; protected set; } /// /// 处理耗时(单位:毫秒) /// - public long ProcessTime { protected set; get; } + public long ProcessTime { get; protected set; } // 加载耗时统计 private Stopwatch _watch = null; @@ -449,9 +459,13 @@ namespace YooAsset double s = System.Math.Floor(spawnTime - m * 60 - h * 3600); return h.ToString("00") + ":" + m.ToString("00") + ":" + s.ToString("00"); } + + /// + /// 检测添加子任务是否会形成循环依赖 + /// 使用深度优先搜索(DFS)遍历子任务图 + /// private bool WouldCreateCycle(AsyncOperationBase child) { - const int maxVisited = 4096; var stack = new Stack(); var visited = new HashSet(); stack.Push(child); @@ -462,18 +476,22 @@ namespace YooAsset if (node == null) continue; + // 防止重复访问 if (visited.Add(node) == false) continue; - if (visited.Count > maxVisited) + // 防止无限循环(图过大) + if (visited.Count > MaxCycleCheckDepth) throw new YooInternalException("Child operation graph is too large, cycle check aborted !"); + // 检测循环:如果遍历到自己,说明形成循环 if (ReferenceEquals(node, this)) return true; if (node._childs == null) continue; + // 将子节点加入栈 for (int i = 0; i < node._childs.Count; i++) { stack.Push(node._childs[i]); diff --git a/Assets/YooAsset/Runtime/OperationSystem/OperationScheduler.cs b/Assets/YooAsset/Runtime/OperationSystem/OperationScheduler.cs index a146543f..64b0b398 100644 --- a/Assets/YooAsset/Runtime/OperationSystem/OperationScheduler.cs +++ b/Assets/YooAsset/Runtime/OperationSystem/OperationScheduler.cs @@ -10,12 +10,12 @@ namespace YooAsset { private readonly List _operations = new List(100); private readonly List _newList = new List(100); - private uint _priority = 0; + private uint _priority; /// /// 所属包裹名称 /// - public string PackageName { private set; get; } + public string PackageName { get; private set; } /// /// 调度器优先级(值越大越优先) @@ -36,12 +36,12 @@ namespace YooAsset /// /// 优先级是否已变更(需要重新排序) /// - public bool IsDirty { set; get; } = false; + public bool IsDirty { get; set; } /// /// 创建顺序(用于同优先级稳定排序) /// - public int CreateIndex { private set; get; } + public int CreateIndex { get; private set; } public OperationScheduler(string packageName, int createIndex) @@ -53,6 +53,9 @@ namespace YooAsset /// /// 开始处理异步操作 /// + /// + /// 操作会先添加到临时队列,在下一次Update时才会开始执行 + /// public void StartOperation(AsyncOperationBase operation) { _newList.Add(operation); diff --git a/Assets/YooAsset/Runtime/OperationSystem/OperationSystem.cs b/Assets/YooAsset/Runtime/OperationSystem/OperationSystem.cs index e686ea35..8f1139c7 100644 --- a/Assets/YooAsset/Runtime/OperationSystem/OperationSystem.cs +++ b/Assets/YooAsset/Runtime/OperationSystem/OperationSystem.cs @@ -15,13 +15,13 @@ namespace YooAsset } #endif - // 全局调度器名称 - public const string GLOBAL_SCHEDULER_NAME = "YOOASSET_GLOBAL_SCHEDULER"; + public const string GlobalSchedulerName = "YOOASSET_GLOBAL_SCHEDULER"; // 全局调度器名称 + private const long MinTimeSlice = 10; // 最小时间片(毫秒) private static readonly Dictionary _schedulerDic = new Dictionary(100); private static readonly List _schedulerList = new List(100); - private static bool _isInitialize = false; - private static int _createIndex = 0; + private static bool _isInitialized; + private static int _createIndex; // 计时器相关 private static Stopwatch _watch; @@ -33,12 +33,16 @@ namespace YooAsset /// public static long MaxTimeSlice { + get + { + return _maxTimeSlice; + } set { - if (value < 10) + if (value < MinTimeSlice) { - _maxTimeSlice = 10; - YooLogger.Warning($"MaxTimeSlice minimum value is 10 milliseconds."); + _maxTimeSlice = MinTimeSlice; + YooLogger.Warning($"MaxTimeSlice minimum value is {MinTimeSlice} milliseconds."); } else { @@ -71,14 +75,17 @@ namespace YooAsset /// public static void Initialize() { - if (_isInitialize == false) + if (_isInitialized) { - _isInitialize = true; - _watch = Stopwatch.StartNew(); - - // 创建全局调度器 - CreatePackageScheduler(GLOBAL_SCHEDULER_NAME, uint.MaxValue); + YooLogger.Warning("Operation system is already initialized!"); + return; } + + _isInitialized = true; + _watch = Stopwatch.StartNew(); + + // 创建全局调度器 + CreatePackageScheduler(GlobalSchedulerName, uint.MaxValue); } /// @@ -86,7 +93,7 @@ namespace YooAsset /// public static void Update() { - if (_isInitialize == false) + if (_isInitialized == false) return; // 检测是否需要执行排序 @@ -122,8 +129,7 @@ namespace YooAsset /// public static void DestroyAll() { - _isInitialize = false; - YooLogger.Log("Operation system destroy all !"); + _isInitialized = false; // 清空所有调度器 foreach (var scheduler in _schedulerList) @@ -136,7 +142,7 @@ namespace YooAsset _watch = null; _frameTime = 0; - MaxTimeSlice = long.MaxValue; + _maxTimeSlice = long.MaxValue; } /// @@ -144,7 +150,7 @@ namespace YooAsset /// public static OperationScheduler CreatePackageScheduler(string packageName, uint priority) { - DebugCheckInitialize(packageName); + DebugEnsureInitialized(packageName); if (_schedulerDic.ContainsKey(packageName)) { @@ -163,10 +169,10 @@ namespace YooAsset /// public static void DestroyPackageScheduler(string packageName) { - DebugCheckInitialize(packageName); + DebugEnsureInitialized(packageName); // 不允许销毁默认调度器 - if (packageName == GLOBAL_SCHEDULER_NAME) + if (packageName == GlobalSchedulerName) { throw new YooInternalException("Cannot destroy the global package scheduler!"); } @@ -184,7 +190,7 @@ namespace YooAsset /// public static void ClearPackageOperation(string packageName) { - DebugCheckInitialize(packageName); + DebugEnsureInitialized(packageName); var scheduler = GetScheduler(packageName); scheduler.ClearAll(); @@ -195,7 +201,7 @@ namespace YooAsset /// public static void StartOperation(string packageName, AsyncOperationBase operation) { - DebugCheckInitialize(packageName); + DebugEnsureInitialized(packageName); var scheduler = GetScheduler(packageName); scheduler.StartOperation(operation); @@ -206,7 +212,7 @@ namespace YooAsset /// public static void SetSchedulerPriority(string packageName, uint priority) { - DebugCheckInitialize(packageName); + DebugEnsureInitialized(packageName); var scheduler = GetScheduler(packageName); scheduler.Priority = priority; @@ -217,7 +223,7 @@ namespace YooAsset /// public static uint GetSchedulerPriority(string packageName) { - DebugCheckInitialize(packageName); + DebugEnsureInitialized(packageName); var scheduler = GetScheduler(packageName); return scheduler.Priority; @@ -240,7 +246,7 @@ namespace YooAsset #region 调试信息 internal static List GetDebugOperationInfos(string packageName) { - DebugCheckInitialize(packageName); + DebugEnsureInitialized(packageName); var scheduler = GetScheduler(packageName); return scheduler.GetDebugOperationInfos(); @@ -249,12 +255,12 @@ namespace YooAsset #region 调试方法 [Conditional("DEBUG")] - private static void DebugCheckInitialize(string packageName) + private static void DebugEnsureInitialized(string packageName) { if (string.IsNullOrWhiteSpace(packageName)) throw new YooInternalException("Package name is null or empty."); - if (_isInitialize == false) + if (_isInitialized == false) throw new YooInternalException($"{nameof(OperationSystem)} not initialized !"); } #endregion diff --git a/Assets/YooAsset/Runtime/ResourcePackage/FileSystemHost.cs b/Assets/YooAsset/Runtime/ResourcePackage/FileSystemHost.cs index 092512a5..cd0ef411 100644 --- a/Assets/YooAsset/Runtime/ResourcePackage/FileSystemHost.cs +++ b/Assets/YooAsset/Runtime/ResourcePackage/FileSystemHost.cs @@ -12,7 +12,7 @@ namespace YooAsset /// /// 当前激活的清单 /// - public PackageManifest ActiveManifest { private set; get; } + public PackageManifest ActiveManifest { get; private set; } public FileSystemHost(string packageName) @@ -75,8 +75,10 @@ namespace YooAsset /// /// 获取主文件系统 - /// 说明:文件系统列表里,最后一个属于主文件系统 /// + /// + /// 文件系统列表里,最后一个属于主文件系统 + /// public IFileSystem GetMainFileSystem() { int count = FileSystems.Count; @@ -123,7 +125,7 @@ namespace YooAsset if (assetInfo == null || assetInfo.IsInvalid) throw new YooInternalException(); - // 注意:如果清单里未找到资源包会抛出异常! + // 注意:如果清单里未找到资源包会抛出异常 var packageBundle = ActiveManifest.GetMainPackageBundle(assetInfo.Asset); return CreateBundleInfo(packageBundle); } @@ -161,6 +163,8 @@ namespace YooAsset #endregion #region 下载器相关 + private const int DefaultBundleInfoCapacity = 1000; + public bool IsNeedDownloadFromRemoteInternal(AssetInfo assetInfo) { if (assetInfo.IsInvalid) @@ -183,6 +187,20 @@ namespace YooAsset return false; } + private delegate bool NeedPredicate(IFileSystem fileSystem, PackageBundle bundle); + private bool NeedDownload(IFileSystem fileSystem, PackageBundle bundle) + { + return fileSystem.NeedDownload(bundle); + } + private bool NeedUnpack(IFileSystem fileSystem, PackageBundle bundle) + { + return fileSystem.NeedUnpack(bundle); + } + private bool NeedImport(IFileSystem fileSystem, PackageBundle bundle) + { + return fileSystem.NeedImport(bundle); + } + public ResourceDownloaderOperation CreateResourceDownloader(ResourceDownloaderOptions options) { return CreateResourceDownloader(ActiveManifest, options); @@ -191,9 +209,9 @@ namespace YooAsset { List downloadList; if (options.Tags == null) - downloadList = GetDownloadListByAll(manifest); + downloadList = GetBundleListByAll(manifest, NeedDownload); else - downloadList = GetDownloadListByTags(manifest, options.Tags); + downloadList = GetBundleListByTags(manifest, options.Tags, NeedDownload); var operation = new ResourceDownloaderOperation(PackageName, downloadList, options.MaximumConcurrency, options.FailedTryAgain); return operation; @@ -207,9 +225,9 @@ namespace YooAsset { List downloadList; if (options.AssetInfos == null) - downloadList = GetDownloadListByAll(manifest); + downloadList = GetBundleListByAll(manifest, NeedDownload); else - downloadList = GetDownloadListByAssetInfos(manifest, options.AssetInfos, options.DownloadBundleDependencies); + downloadList = GetBundleListByAssetInfos(manifest, options.AssetInfos, options.DownloadBundleDependencies, NeedDownload); var operation = new ResourceDownloaderOperation(PackageName, downloadList, options.MaximumConcurrency, options.FailedTryAgain); return operation; @@ -221,13 +239,13 @@ namespace YooAsset } public ResourceUnpackerOperation CreateResourceUnpacker(PackageManifest manifest, ResourceUnpackerOptions options) { - List unpcakList; + List unpackList; if (options.Tags == null) - unpcakList = GetUnpackListByAll(manifest); + unpackList = GetBundleListByAll(manifest, NeedUnpack); else - unpcakList = GetUnpackListByTags(manifest, options.Tags); + unpackList = GetBundleListByTags(manifest, options.Tags, NeedUnpack); - var operation = new ResourceUnpackerOperation(PackageName, unpcakList, options.MaximumConcurrency, options.FailedTryAgain); + var operation = new ResourceUnpackerOperation(PackageName, unpackList, options.MaximumConcurrency, options.FailedTryAgain); return operation; } @@ -237,24 +255,24 @@ namespace YooAsset } public ResourceImporterOperation CreateResourceImporter(PackageManifest manifest, BundleImporterOptions options) { - List importerList = GetImporterListByBundleInfos(manifest, options.BundleInfos); + List importerList = GetBundleListByBundleInfos(manifest, options.BundleInfos, NeedImport); var operation = new ResourceImporterOperation(PackageName, importerList, options.MaximumConcurrency, options.FailedTryAgain); return operation; } - private List GetDownloadListByAll(PackageManifest manifest) + private List GetBundleListByAll(PackageManifest manifest, Func predicate) { if (manifest == null) return new List(); - List result = new List(1000); + List result = new List(DefaultBundleInfoCapacity); foreach (var packageBundle in manifest.BundleList) { var fileSystem = GetBelongFileSystem(packageBundle); if (fileSystem == null) continue; - if (fileSystem.NeedDownload(packageBundle)) + if (predicate(fileSystem, packageBundle)) { var bundleInfo = new BundleInfo(fileSystem, packageBundle); result.Add(bundleInfo); @@ -262,21 +280,21 @@ namespace YooAsset } return result; } - private List GetDownloadListByTags(PackageManifest manifest, string[] tags) + private List GetBundleListByTags(PackageManifest manifest, string[] tags, Func predicate) { if (manifest == null) return new List(); - List result = new List(1000); + List result = new List(DefaultBundleInfoCapacity); foreach (var packageBundle in manifest.BundleList) { var fileSystem = GetBelongFileSystem(packageBundle); if (fileSystem == null) continue; - if (fileSystem.NeedDownload(packageBundle)) + if (predicate(fileSystem, packageBundle)) { - // 如果未带任何标记,则统一下载 + // 注意:如果未带任何标记,则统一处理 if (packageBundle.HasAnyTags() == false) { var bundleInfo = new BundleInfo(fileSystem, packageBundle); @@ -284,7 +302,6 @@ namespace YooAsset } else { - // 查询DLC资源 if (packageBundle.HasTag(tags)) { var bundleInfo = new BundleInfo(fileSystem, packageBundle); @@ -295,7 +312,7 @@ namespace YooAsset } return result; } - private List GetDownloadListByAssetInfos(PackageManifest manifest, AssetInfo[] assetInfos, bool recursiveDownload) + private List GetBundleListByAssetInfos(PackageManifest manifest, AssetInfo[] assetInfos, bool recursiveDepend, Func predicate) { if (manifest == null) return new List(); @@ -331,7 +348,7 @@ namespace YooAsset } // 下载主资源包内所有资源对象依赖的资源包 - if (recursiveDownload) + if (recursiveDepend) { foreach (var otherMainAsset in mainBundle.IncludeMainAssets) { @@ -355,14 +372,14 @@ namespace YooAsset } } - List result = new List(1000); + List result = new List(DefaultBundleInfoCapacity); foreach (var packageBundle in checkList) { var fileSystem = GetBelongFileSystem(packageBundle); if (fileSystem == null) continue; - if (fileSystem.NeedDownload(packageBundle)) + if (predicate(fileSystem, packageBundle)) { var bundleInfo = new BundleInfo(fileSystem, packageBundle); result.Add(bundleInfo); @@ -370,62 +387,19 @@ namespace YooAsset } return result; } - private List GetUnpackListByAll(PackageManifest manifest) + private List GetBundleListByBundleInfos(PackageManifest manifest, ImportBundleInfo[] fileInfos, Func predicate) { if (manifest == null) return new List(); - List result = new List(1000); - foreach (var packageBundle in manifest.BundleList) - { - var fileSystem = GetBelongFileSystem(packageBundle); - if (fileSystem == null) - continue; - - if (fileSystem.NeedUnpack(packageBundle)) - { - var bundleInfo = new BundleInfo(fileSystem, packageBundle); - result.Add(bundleInfo); - } - } - return result; - } - private List GetUnpackListByTags(PackageManifest manifest, string[] tags) - { - if (manifest == null) - return new List(); - - List result = new List(1000); - foreach (var packageBundle in manifest.BundleList) - { - var fileSystem = GetBelongFileSystem(packageBundle); - if (fileSystem == null) - continue; - - if (fileSystem.NeedUnpack(packageBundle)) - { - if (packageBundle.HasTag(tags)) - { - var bundleInfo = new BundleInfo(fileSystem, packageBundle); - result.Add(bundleInfo); - } - } - } - return result; - } - private List GetImporterListByBundleInfos(PackageManifest manifest, ImportBundleInfo[] fileInfos) - { - if (manifest == null) - return new List(); - - List result = new List(); + List result = new List(DefaultBundleInfoCapacity); foreach (var fileInfo in fileInfos) { string filePath = fileInfo.FilePath; if (string.IsNullOrEmpty(filePath)) continue; - PackageBundle packageBundle = null; + PackageBundle packageBundle; if (string.IsNullOrEmpty(fileInfo.BundleName) == false) { if (manifest.TryGetPackageBundleByBundleName(fileInfo.BundleName, out packageBundle) == false) @@ -458,7 +432,7 @@ namespace YooAsset if (fileSystem == null) continue; - if (fileSystem.NeedImport(packageBundle)) + if (predicate(fileSystem, packageBundle)) { var bundleInfo = new BundleInfo(fileSystem, packageBundle, filePath); result.Add(bundleInfo); diff --git a/Assets/YooAsset/Runtime/ResourcePackage/Operation/InitializePackageOperation.cs b/Assets/YooAsset/Runtime/ResourcePackage/Operation/InitializePackageOperation.cs index f9df2e30..ebae1fd1 100644 --- a/Assets/YooAsset/Runtime/ResourcePackage/Operation/InitializePackageOperation.cs +++ b/Assets/YooAsset/Runtime/ResourcePackage/Operation/InitializePackageOperation.cs @@ -51,7 +51,6 @@ namespace YooAsset else throw new NotImplementedException($"{_options.GetType().Name}"); - _package._playMode = _playMode; _steps = ESteps.CheckOptions; } @@ -122,8 +121,7 @@ namespace YooAsset resourceManager.Initialize(_options, fileSystemHost); _fileSystemHost = fileSystemHost; - _package._fileSystemHost = fileSystemHost; - _package._resourceManager = resourceManager; + _package.InternalInitialize(resourceManager, fileSystemHost); _steps = ESteps.InitFileSystem; } diff --git a/Assets/YooAsset/Runtime/ResourcePackage/ResourcePackage.cs b/Assets/YooAsset/Runtime/ResourcePackage/ResourcePackage.cs index b2a75907..93442326 100644 --- a/Assets/YooAsset/Runtime/ResourcePackage/ResourcePackage.cs +++ b/Assets/YooAsset/Runtime/ResourcePackage/ResourcePackage.cs @@ -9,9 +9,8 @@ namespace YooAsset public class ResourcePackage { private InitializePackageOperation _initializeOp; - internal ResourceManager _resourceManager; - internal FileSystemHost _fileSystemHost; - internal EPlayMode _playMode; + private ResourceManager _resourceManager; + private FileSystemHost _fileSystemHost; /// /// 包裹名 @@ -53,15 +52,16 @@ namespace YooAsset set { OperationSystem.SetSchedulerPriority(PackageName, value); } } - + internal ResourcePackage(string packageName) { PackageName = packageName; } - - /// - /// 销毁资源包裹 - /// + internal void InternalInitialize(ResourceManager manager, FileSystemHost host) + { + _resourceManager = manager; + _fileSystemHost = host; + } internal void InternalDestroy() { _initializeOp = null; @@ -91,7 +91,7 @@ namespace YooAsset // 检测重复初始化 if (_initializeOp != null) - throw new YooPackageException(PackageName, $"Package '{PackageName}' is already initialized !"); + throw new YooPackageException(PackageName, $"Resource package '{PackageName}' is already initialized!"); // 开始初始化操作 _initializeOp = new InitializePackageOperation(this, options); @@ -113,7 +113,7 @@ namespace YooAsset { var options = new UnloadAllAssetsOptions(true, true); var operation = new DestroyPackageOperation(this, options); - OperationSystem.StartOperation(OperationSystem.GLOBAL_SCHEDULER_NAME, operation); + OperationSystem.StartOperation(OperationSystem.GlobalSchedulerName, operation); return operation; } @@ -123,7 +123,8 @@ namespace YooAsset /// public RequestPackageVersionOperation RequestPackageVersionAsync() { - var options = new RequestPackageVersionOptions(true, 60); + int defaultTimeout = 60; + var options = new RequestPackageVersionOptions(true, defaultTimeout); return RequestPackageVersionAsync(options); } @@ -132,7 +133,7 @@ namespace YooAsset /// public RequestPackageVersionOperation RequestPackageVersionAsync(RequestPackageVersionOptions options) { - DebugCheckInitialize(false); + EnsureInitialized(false); var operation = new RequestPackageVersionOperation(_fileSystemHost, options); OperationSystem.StartOperation(PackageName, operation); return operation; @@ -143,12 +144,12 @@ namespace YooAsset /// public LoadPackageManifestOperation LoadPackageManifestAsync(LoadPackageManifestOptions options) { - DebugCheckInitialize(false); + EnsureInitialized(false); // 注意:强烈建议在更新之前保持加载器为空! if (_resourceManager.HasAnyLoader()) { - YooLogger.Warning($"Found loaded bundle before update manifest ! Recommended to call the {nameof(UnloadAllAssetsAsync)} method to release loaded bundle !"); + YooLogger.Warning($"Found loaded bundle before update manifest ! Recommended to call the {nameof(UnloadAllAssetsAsync)} method to release loaded bundle !"); } var operation = new LoadPackageManifestOperation(_fileSystemHost, options); @@ -161,7 +162,7 @@ namespace YooAsset /// public PreDownloadContentOperation PreDownloadContentAsync(PreDownloadContentOptions options) { - DebugCheckInitialize(false); + EnsureInitialized(false); var operation = new PreDownloadContentOperation(_fileSystemHost, options); OperationSystem.StartOperation(PackageName, operation); return operation; @@ -172,7 +173,7 @@ namespace YooAsset /// public ClearCacheFilesOperation ClearCacheFilesAsync(ClearCacheFilesOptions options) { - DebugCheckInitialize(false); + EnsureInitialized(false); options.Manifest = _fileSystemHost.ActiveManifest; var operation = new ClearCacheFilesOperation(_fileSystemHost, options); OperationSystem.StartOperation(PackageName, operation); @@ -186,7 +187,7 @@ namespace YooAsset /// public string GetPackageVersion() { - DebugCheckInitialize(); + EnsureInitialized(); return _fileSystemHost.ActiveManifest.PackageVersion; } @@ -195,7 +196,7 @@ namespace YooAsset /// public string GetPackageNote() { - DebugCheckInitialize(); + EnsureInitialized(); return _fileSystemHost.ActiveManifest.PackageNote; } @@ -204,7 +205,7 @@ namespace YooAsset /// public PackageDetails GetPackageDetails() { - DebugCheckInitialize(); + EnsureInitialized(); return _fileSystemHost.ActiveManifest.GetPackageDetails(); } #endregion @@ -225,7 +226,7 @@ namespace YooAsset /// 卸载选项 public UnloadAllAssetsOperation UnloadAllAssetsAsync(UnloadAllAssetsOptions options) { - DebugCheckInitialize(); + EnsureInitialized(); var operation = new UnloadAllAssetsOperation(_resourceManager, options); OperationSystem.StartOperation(PackageName, operation); return operation; @@ -238,7 +239,8 @@ namespace YooAsset /// public UnloadUnusedAssetsOperation UnloadUnusedAssetsAsync() { - var options = new UnloadUnusedAssetsOptions(10); + int defaultLoopCount = 10; + var options = new UnloadUnusedAssetsOptions(defaultLoopCount); return UnloadUnusedAssetsAsync(options); } @@ -248,7 +250,7 @@ namespace YooAsset /// public UnloadUnusedAssetsOperation UnloadUnusedAssetsAsync(UnloadUnusedAssetsOptions options) { - DebugCheckInitialize(); + EnsureInitialized(); var operation = new UnloadUnusedAssetsOperation(_resourceManager, options); OperationSystem.StartOperation(PackageName, operation); return operation; @@ -260,7 +262,7 @@ namespace YooAsset /// public void TryUnloadUnusedAsset(string location, int loopCount = 10) { - DebugCheckInitialize(); + EnsureInitialized(); AssetInfo assetInfo = ConvertLocationToAssetInfo(location, null); _resourceManager.TryUnloadUnusedAsset(assetInfo, loopCount); } @@ -271,7 +273,7 @@ namespace YooAsset /// public void TryUnloadUnusedAsset(AssetInfo assetInfo, int loopCount = 10) { - DebugCheckInitialize(); + EnsureInitialized(); _resourceManager.TryUnloadUnusedAsset(assetInfo, loopCount); } #endregion @@ -283,7 +285,7 @@ namespace YooAsset /// 资源的定位地址 public bool IsNeedDownloadFromRemote(string location) { - DebugCheckInitialize(); + EnsureInitialized(); AssetInfo assetInfo = ConvertLocationToAssetInfo(location, null); return _fileSystemHost.IsNeedDownloadFromRemoteInternal(assetInfo); } @@ -294,7 +296,7 @@ namespace YooAsset /// 资源的定位地址 public bool IsNeedDownloadFromRemote(AssetInfo assetInfo) { - DebugCheckInitialize(); + EnsureInitialized(); return _fileSystemHost.IsNeedDownloadFromRemoteInternal(assetInfo); } @@ -303,7 +305,7 @@ namespace YooAsset /// public AssetInfo[] GetAllAssetInfos() { - DebugCheckInitialize(); + EnsureInitialized(); return _fileSystemHost.ActiveManifest.GetAllAssetInfos(); } @@ -313,7 +315,7 @@ namespace YooAsset /// 资源标签 public AssetInfo[] GetAssetInfos(string tag) { - DebugCheckInitialize(); + EnsureInitialized(); string[] tags = new string[] { tag }; return _fileSystemHost.ActiveManifest.GetAssetInfosByTags(tags); } @@ -324,7 +326,7 @@ namespace YooAsset /// 资源标签列表 public AssetInfo[] GetAssetInfos(string[] tags) { - DebugCheckInitialize(); + EnsureInitialized(); return _fileSystemHost.ActiveManifest.GetAssetInfosByTags(tags); } @@ -334,7 +336,7 @@ namespace YooAsset /// 资源的定位地址 public AssetInfo GetAssetInfo(string location) { - DebugCheckInitialize(); + EnsureInitialized(); return ConvertLocationToAssetInfo(location, null); } @@ -345,7 +347,7 @@ namespace YooAsset /// 资源类型 public AssetInfo GetAssetInfo(string location, System.Type type) { - DebugCheckInitialize(); + EnsureInitialized(); return ConvertLocationToAssetInfo(location, type); } @@ -355,7 +357,7 @@ namespace YooAsset /// 资源GUID public AssetInfo GetAssetInfoByGUID(string assetGUID) { - DebugCheckInitialize(); + EnsureInitialized(); return ConvertAssetGUIDToAssetInfo(assetGUID, null); } @@ -366,7 +368,7 @@ namespace YooAsset /// 资源类型 public AssetInfo GetAssetInfoByGUID(string assetGUID, System.Type type) { - DebugCheckInitialize(); + EnsureInitialized(); return ConvertAssetGUIDToAssetInfo(assetGUID, type); } @@ -376,7 +378,7 @@ namespace YooAsset /// 资源的定位地址 public bool CheckLocationValid(string location) { - DebugCheckInitialize(); + EnsureInitialized(); string assetPath = _fileSystemHost.ActiveManifest.TryMappingToAssetPath(location); return string.IsNullOrEmpty(assetPath) == false; } @@ -389,7 +391,7 @@ namespace YooAsset /// 资源信息 public RawFileHandle LoadRawFileSync(AssetInfo assetInfo) { - DebugCheckInitialize(); + EnsureInitialized(); return LoadRawFileInternal(assetInfo, true, 0); } @@ -399,7 +401,7 @@ namespace YooAsset /// 资源的定位地址 public RawFileHandle LoadRawFileSync(string location) { - DebugCheckInitialize(); + EnsureInitialized(); AssetInfo assetInfo = ConvertLocationToAssetInfo(location, null); return LoadRawFileInternal(assetInfo, true, 0); } @@ -411,7 +413,7 @@ namespace YooAsset /// 加载的优先级 public RawFileHandle LoadRawFileAsync(AssetInfo assetInfo, uint priority = 0) { - DebugCheckInitialize(); + EnsureInitialized(); return LoadRawFileInternal(assetInfo, false, priority); } @@ -422,7 +424,7 @@ namespace YooAsset /// 加载的优先级 public RawFileHandle LoadRawFileAsync(string location, uint priority = 0) { - DebugCheckInitialize(); + EnsureInitialized(); AssetInfo assetInfo = ConvertLocationToAssetInfo(location, null); return LoadRawFileInternal(assetInfo, false, priority); } @@ -447,7 +449,7 @@ namespace YooAsset /// 场景物理模式 public SceneHandle LoadSceneSync(string location, LoadSceneMode sceneMode = LoadSceneMode.Single, LocalPhysicsMode physicsMode = LocalPhysicsMode.None) { - DebugCheckInitialize(); + EnsureInitialized(); AssetInfo assetInfo = ConvertLocationToAssetInfo(location, null); return LoadSceneInternal(assetInfo, true, sceneMode, physicsMode, false, 0); } @@ -460,7 +462,7 @@ namespace YooAsset /// 场景物理模式 public SceneHandle LoadSceneSync(AssetInfo assetInfo, LoadSceneMode sceneMode = LoadSceneMode.Single, LocalPhysicsMode physicsMode = LocalPhysicsMode.None) { - DebugCheckInitialize(); + EnsureInitialized(); return LoadSceneInternal(assetInfo, true, sceneMode, physicsMode, false, 0); } @@ -474,7 +476,7 @@ namespace YooAsset /// 加载的优先级 public SceneHandle LoadSceneAsync(string location, LoadSceneMode sceneMode = LoadSceneMode.Single, LocalPhysicsMode physicsMode = LocalPhysicsMode.None, bool suspendLoad = false, uint priority = 0) { - DebugCheckInitialize(); + EnsureInitialized(); AssetInfo assetInfo = ConvertLocationToAssetInfo(location, null); return LoadSceneInternal(assetInfo, false, sceneMode, physicsMode, suspendLoad, priority); } @@ -489,13 +491,13 @@ namespace YooAsset /// 加载的优先级 public SceneHandle LoadSceneAsync(AssetInfo assetInfo, LoadSceneMode sceneMode = LoadSceneMode.Single, LocalPhysicsMode physicsMode = LocalPhysicsMode.None, bool suspendLoad = false, uint priority = 0) { - DebugCheckInitialize(); + EnsureInitialized(); return LoadSceneInternal(assetInfo, false, sceneMode, physicsMode, suspendLoad, priority); } private SceneHandle LoadSceneInternal(AssetInfo assetInfo, bool waitForAsyncComplete, LoadSceneMode sceneMode, LocalPhysicsMode physicsMode, bool suspendLoad, uint priority) { - DebugCheckAssetLoadType(assetInfo.AssetType); + DebugEnsureAssetType(assetInfo.AssetType); assetInfo.LoadMethod = AssetInfo.ELoadMethod.LoadScene; var loadSceneParams = new LoadSceneParameters(sceneMode, physicsMode); var handle = _resourceManager.LoadSceneAsync(assetInfo, loadSceneParams, suspendLoad, priority); @@ -505,14 +507,14 @@ namespace YooAsset } #endregion - #region 资源加载 + #region 资源加载 [主资源] /// /// 同步加载资源对象 /// /// 资源信息 public AssetHandle LoadAssetSync(AssetInfo assetInfo) { - DebugCheckInitialize(); + EnsureInitialized(); return LoadAssetInternal(assetInfo, true, 0); } @@ -523,7 +525,7 @@ namespace YooAsset /// 资源的定位地址 public AssetHandle LoadAssetSync(string location) where TObject : UnityEngine.Object { - DebugCheckInitialize(); + EnsureInitialized(); AssetInfo assetInfo = ConvertLocationToAssetInfo(location, typeof(TObject)); return LoadAssetInternal(assetInfo, true, 0); } @@ -535,7 +537,7 @@ namespace YooAsset /// 资源类型 public AssetHandle LoadAssetSync(string location, System.Type type) { - DebugCheckInitialize(); + EnsureInitialized(); AssetInfo assetInfo = ConvertLocationToAssetInfo(location, type); return LoadAssetInternal(assetInfo, true, 0); } @@ -546,9 +548,8 @@ namespace YooAsset /// 资源的定位地址 public AssetHandle LoadAssetSync(string location) { - DebugCheckInitialize(); - Type type = typeof(UnityEngine.Object); - AssetInfo assetInfo = ConvertLocationToAssetInfo(location, type); + EnsureInitialized(); + AssetInfo assetInfo = ConvertLocationToAssetInfo(location, typeof(UnityEngine.Object)); return LoadAssetInternal(assetInfo, true, 0); } @@ -560,7 +561,7 @@ namespace YooAsset /// 加载的优先级 public AssetHandle LoadAssetAsync(AssetInfo assetInfo, uint priority = 0) { - DebugCheckInitialize(); + EnsureInitialized(); return LoadAssetInternal(assetInfo, false, priority); } @@ -572,7 +573,7 @@ namespace YooAsset /// 加载的优先级 public AssetHandle LoadAssetAsync(string location, uint priority = 0) where TObject : UnityEngine.Object { - DebugCheckInitialize(); + EnsureInitialized(); AssetInfo assetInfo = ConvertLocationToAssetInfo(location, typeof(TObject)); return LoadAssetInternal(assetInfo, false, priority); } @@ -585,7 +586,7 @@ namespace YooAsset /// 加载的优先级 public AssetHandle LoadAssetAsync(string location, System.Type type, uint priority = 0) { - DebugCheckInitialize(); + EnsureInitialized(); AssetInfo assetInfo = ConvertLocationToAssetInfo(location, type); return LoadAssetInternal(assetInfo, false, priority); } @@ -597,16 +598,15 @@ namespace YooAsset /// 加载的优先级 public AssetHandle LoadAssetAsync(string location, uint priority = 0) { - DebugCheckInitialize(); - Type type = typeof(UnityEngine.Object); - AssetInfo assetInfo = ConvertLocationToAssetInfo(location, type); + EnsureInitialized(); + AssetInfo assetInfo = ConvertLocationToAssetInfo(location, typeof(UnityEngine.Object)); return LoadAssetInternal(assetInfo, false, priority); } private AssetHandle LoadAssetInternal(AssetInfo assetInfo, bool waitForAsyncComplete, uint priority) { - DebugCheckAssetLoadType(assetInfo.AssetType); + DebugEnsureAssetType(assetInfo.AssetType); assetInfo.LoadMethod = AssetInfo.ELoadMethod.LoadAsset; var handle = _resourceManager.LoadAssetAsync(assetInfo, priority); if (waitForAsyncComplete) @@ -615,14 +615,14 @@ namespace YooAsset } #endregion - #region 资源加载 + #region 资源加载 [子资源] /// /// 同步加载子资源对象 /// /// 资源信息 public SubAssetsHandle LoadSubAssetsSync(AssetInfo assetInfo) { - DebugCheckInitialize(); + EnsureInitialized(); return LoadSubAssetsInternal(assetInfo, true, 0); } @@ -633,7 +633,7 @@ namespace YooAsset /// 资源的定位地址 public SubAssetsHandle LoadSubAssetsSync(string location) where TObject : UnityEngine.Object { - DebugCheckInitialize(); + EnsureInitialized(); AssetInfo assetInfo = ConvertLocationToAssetInfo(location, typeof(TObject)); return LoadSubAssetsInternal(assetInfo, true, 0); } @@ -645,7 +645,7 @@ namespace YooAsset /// 子对象类型 public SubAssetsHandle LoadSubAssetsSync(string location, System.Type type) { - DebugCheckInitialize(); + EnsureInitialized(); AssetInfo assetInfo = ConvertLocationToAssetInfo(location, type); return LoadSubAssetsInternal(assetInfo, true, 0); } @@ -656,9 +656,8 @@ namespace YooAsset /// 资源的定位地址 public SubAssetsHandle LoadSubAssetsSync(string location) { - DebugCheckInitialize(); - Type type = typeof(UnityEngine.Object); - AssetInfo assetInfo = ConvertLocationToAssetInfo(location, type); + EnsureInitialized(); + AssetInfo assetInfo = ConvertLocationToAssetInfo(location, typeof(UnityEngine.Object)); return LoadSubAssetsInternal(assetInfo, true, 0); } @@ -670,7 +669,7 @@ namespace YooAsset /// 加载的优先级 public SubAssetsHandle LoadSubAssetsAsync(AssetInfo assetInfo, uint priority = 0) { - DebugCheckInitialize(); + EnsureInitialized(); return LoadSubAssetsInternal(assetInfo, false, priority); } @@ -682,7 +681,7 @@ namespace YooAsset /// 加载的优先级 public SubAssetsHandle LoadSubAssetsAsync(string location, uint priority = 0) where TObject : UnityEngine.Object { - DebugCheckInitialize(); + EnsureInitialized(); AssetInfo assetInfo = ConvertLocationToAssetInfo(location, typeof(TObject)); return LoadSubAssetsInternal(assetInfo, false, priority); } @@ -695,7 +694,7 @@ namespace YooAsset /// 加载的优先级 public SubAssetsHandle LoadSubAssetsAsync(string location, System.Type type, uint priority = 0) { - DebugCheckInitialize(); + EnsureInitialized(); AssetInfo assetInfo = ConvertLocationToAssetInfo(location, type); return LoadSubAssetsInternal(assetInfo, false, priority); } @@ -707,16 +706,15 @@ namespace YooAsset /// 加载的优先级 public SubAssetsHandle LoadSubAssetsAsync(string location, uint priority = 0) { - DebugCheckInitialize(); - Type type = typeof(UnityEngine.Object); - AssetInfo assetInfo = ConvertLocationToAssetInfo(location, type); + EnsureInitialized(); + AssetInfo assetInfo = ConvertLocationToAssetInfo(location, typeof(UnityEngine.Object)); return LoadSubAssetsInternal(assetInfo, false, priority); } private SubAssetsHandle LoadSubAssetsInternal(AssetInfo assetInfo, bool waitForAsyncComplete, uint priority) { - DebugCheckAssetLoadType(assetInfo.AssetType); + DebugEnsureAssetType(assetInfo.AssetType); assetInfo.LoadMethod = AssetInfo.ELoadMethod.LoadSubAssets; var handle = _resourceManager.LoadSubAssetsAsync(assetInfo, priority); if (waitForAsyncComplete) @@ -725,14 +723,14 @@ namespace YooAsset } #endregion - #region 资源加载 + #region 资源加载 [全部资源] /// /// 同步加载资源包内所有资源对象 /// /// 资源信息 public AllAssetsHandle LoadAllAssetsSync(AssetInfo assetInfo) { - DebugCheckInitialize(); + EnsureInitialized(); return LoadAllAssetsInternal(assetInfo, true, 0); } @@ -743,7 +741,7 @@ namespace YooAsset /// 资源的定位地址 public AllAssetsHandle LoadAllAssetsSync(string location) where TObject : UnityEngine.Object { - DebugCheckInitialize(); + EnsureInitialized(); AssetInfo assetInfo = ConvertLocationToAssetInfo(location, typeof(TObject)); return LoadAllAssetsInternal(assetInfo, true, 0); } @@ -755,7 +753,7 @@ namespace YooAsset /// 子对象类型 public AllAssetsHandle LoadAllAssetsSync(string location, System.Type type) { - DebugCheckInitialize(); + EnsureInitialized(); AssetInfo assetInfo = ConvertLocationToAssetInfo(location, type); return LoadAllAssetsInternal(assetInfo, true, 0); } @@ -766,9 +764,8 @@ namespace YooAsset /// 资源的定位地址 public AllAssetsHandle LoadAllAssetsSync(string location) { - DebugCheckInitialize(); - Type type = typeof(UnityEngine.Object); - AssetInfo assetInfo = ConvertLocationToAssetInfo(location, type); + EnsureInitialized(); + AssetInfo assetInfo = ConvertLocationToAssetInfo(location, typeof(UnityEngine.Object)); return LoadAllAssetsInternal(assetInfo, true, 0); } @@ -780,7 +777,7 @@ namespace YooAsset /// 加载的优先级 public AllAssetsHandle LoadAllAssetsAsync(AssetInfo assetInfo, uint priority = 0) { - DebugCheckInitialize(); + EnsureInitialized(); return LoadAllAssetsInternal(assetInfo, false, priority); } @@ -792,7 +789,7 @@ namespace YooAsset /// 加载的优先级 public AllAssetsHandle LoadAllAssetsAsync(string location, uint priority = 0) where TObject : UnityEngine.Object { - DebugCheckInitialize(); + EnsureInitialized(); AssetInfo assetInfo = ConvertLocationToAssetInfo(location, typeof(TObject)); return LoadAllAssetsInternal(assetInfo, false, priority); } @@ -805,7 +802,7 @@ namespace YooAsset /// 加载的优先级 public AllAssetsHandle LoadAllAssetsAsync(string location, System.Type type, uint priority = 0) { - DebugCheckInitialize(); + EnsureInitialized(); AssetInfo assetInfo = ConvertLocationToAssetInfo(location, type); return LoadAllAssetsInternal(assetInfo, false, priority); } @@ -817,16 +814,15 @@ namespace YooAsset /// 加载的优先级 public AllAssetsHandle LoadAllAssetsAsync(string location, uint priority = 0) { - DebugCheckInitialize(); - Type type = typeof(UnityEngine.Object); - AssetInfo assetInfo = ConvertLocationToAssetInfo(location, type); + EnsureInitialized(); + AssetInfo assetInfo = ConvertLocationToAssetInfo(location, typeof(UnityEngine.Object)); return LoadAllAssetsInternal(assetInfo, false, priority); } private AllAssetsHandle LoadAllAssetsInternal(AssetInfo assetInfo, bool waitForAsyncComplete, uint priority) { - DebugCheckAssetLoadType(assetInfo.AssetType); + DebugEnsureAssetType(assetInfo.AssetType); assetInfo.LoadMethod = AssetInfo.ELoadMethod.LoadAllAssets; var handle = _resourceManager.LoadAllAssetsAsync(assetInfo, priority); if (waitForAsyncComplete) @@ -841,16 +837,16 @@ namespace YooAsset /// public ResourceDownloaderOperation CreateResourceDownloader(ResourceDownloaderOptions options) { - DebugCheckInitialize(); + EnsureInitialized(); return _fileSystemHost.CreateResourceDownloader(options); } - + /// /// 创建资源下载器,用于下载指定的资源信息列表依赖的资源包文件 /// public ResourceDownloaderOperation CreateResourceDownloader(BundleDownloaderOptions options) { - DebugCheckInitialize(); + EnsureInitialized(); return _fileSystemHost.CreateResourceDownloader(options); } #endregion @@ -861,7 +857,7 @@ namespace YooAsset /// public ResourceUnpackerOperation CreateResourceUnpacker(ResourceUnpackerOptions options) { - DebugCheckInitialize(); + EnsureInitialized(); return _fileSystemHost.CreateResourceUnpacker(options); } #endregion @@ -872,7 +868,7 @@ namespace YooAsset /// public ResourceImporterOperation CreateResourceImporter(BundleImporterOptions options) { - DebugCheckInitialize(); + EnsureInitialized(); return _fileSystemHost.CreateResourceImporter(options); } #endregion @@ -889,47 +885,43 @@ namespace YooAsset #endregion #region 调试方法 - private void DebugCheckInitialize(bool checkActiveManifest = true) + private void EnsureInitialized(bool checkActiveManifest = true) { if (InitializeStatus != EOperationStatus.Succeed) { if (InitializeStatus == EOperationStatus.None) { - throw new YooPackageException(PackageName, "Package not initialize !"); + throw new YooPackageException(PackageName, "Resource package not initialized!"); } else if (InitializeStatus == EOperationStatus.Processing) { - throw new YooPackageException(PackageName, "Package initialize not completed !"); + throw new YooPackageException(PackageName, "Resource package initialization not completed!"); } else if (InitializeStatus == EOperationStatus.Failed) { string error = _initializeOp == null ? string.Empty : _initializeOp.Error; - throw new YooPackageException(PackageName, $"Package initialize failed ! {error}"); + throw new YooPackageException(PackageName, $"Resource package initialization failed! Error : {error}"); } } if (checkActiveManifest) { if (_fileSystemHost.ActiveManifest == null) - throw new YooPackageException(PackageName, "Can not found active package manifest !"); + throw new YooPackageException(PackageName, "Cannot found active package manifest!"); } } [Conditional("DEBUG")] - private void DebugCheckAssetLoadType(System.Type type) + private void DebugEnsureAssetType(System.Type type) { if (type == null) return; if (typeof(UnityEngine.Behaviour).IsAssignableFrom(type)) - { - throw new YooLoadException($"Load asset type is invalid : {type.FullName} !"); - } + throw new YooLoadException($"Load asset type is invalid : {type.FullName}"); if (typeof(UnityEngine.Object).IsAssignableFrom(type) == false) - { - throw new YooLoadException($"Load asset type is invalid : {type.FullName} !"); - } + throw new YooLoadException($"Load asset type is invalid : {type.FullName}"); } #endregion diff --git a/Assets/YooAsset/Runtime/YooAssets.cs b/Assets/YooAsset/Runtime/YooAssets.cs index 490af73a..6dc1e3da 100644 --- a/Assets/YooAsset/Runtime/YooAssets.cs +++ b/Assets/YooAsset/Runtime/YooAssets.cs @@ -13,21 +13,21 @@ namespace YooAsset [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)] private static void OnRuntimeInitialize() { - _isInitialize = false; + _isInitialized = false; _packages.Clear(); } #endif - private static bool _isInitialize = false; - private static GameObject _driver = null; - private static readonly List _packages = new List(); + private static bool _isInitialized; + private static GameObject _driver; + private static readonly Dictionary _packages = new Dictionary(10); /// /// 是否已经初始化 /// public static bool Initialized { - get { return _isInitialize; } + get { return _isInitialized; } } /// @@ -36,31 +36,27 @@ namespace YooAsset /// 自定义日志处理 public static void Initialize(ILogger logger = null) { - if (_isInitialize) + if (_isInitialized) { - UnityEngine.Debug.LogWarning($"{nameof(YooAssets)} is initialized !"); + YooLogger.Warning("YooAssets is already initialized!"); return; } - if (_isInitialize == false) - { - YooLogger.Logger = logger; + YooLogger.Logger = logger; - // 创建驱动器 - _isInitialize = true; - _driver = new UnityEngine.GameObject($"[{nameof(YooAssets)}]"); - _driver.AddComponent(); - UnityEngine.Object.DontDestroyOnLoad(_driver); - YooLogger.Log($"{nameof(YooAssets)} initialize !"); + // 创建驱动器 + _isInitialized = true; + _driver = new UnityEngine.GameObject($"[{nameof(YooAssets)}]"); + _driver.AddComponent(); + UnityEngine.Object.DontDestroyOnLoad(_driver); #if DEBUG - // 添加远程调试脚本 - _driver.AddComponent(); + // 添加远程调试脚本 + _driver.AddComponent(); #endif - // 初始化异步操作系统 - OperationSystem.Initialize(); - } + // 初始化异步操作系统 + OperationSystem.Initialize(); } /// @@ -68,9 +64,9 @@ namespace YooAsset /// public static void Destroy() { - if (_isInitialize) + if (_isInitialized) { - _isInitialize = false; + _isInitialized = false; if (_driver != null) GameObject.Destroy(_driver); @@ -91,35 +87,25 @@ namespace YooAsset /// internal static void Update() { - if (_isInitialize) + if (_isInitialized) { OperationSystem.Update(); } } - /// - /// 创建资源包裹 - /// - /// 包裹名称 - public static ResourcePackage CreatePackage(string packageName) - { - return CreatePackage(packageName, 0); - } - /// /// 创建资源包裹 /// /// 包裹名称 /// 包裹优先级(值越大越优先更新) - public static ResourcePackage CreatePackage(string packageName, uint packagePriority) + public static ResourcePackage CreatePackage(string packageName, uint packagePriority = 0) { - CheckException(packageName); + EnsureInitialized(packageName); if (ContainsPackage(packageName)) - throw new YooPackageException(packageName, $"Package {packageName} already existed ! Cannot create duplicate packages."); + throw new YooPackageException(packageName, $"Resource package {packageName} already existed! Cannot create duplicate packages."); - YooLogger.Log($"Create resource package : {packageName}"); ResourcePackage package = new ResourcePackage(packageName); - _packages.Add(package); + _packages.Add(packageName, package); // 注册包裹调度器 OperationSystem.CreatePackageScheduler(packageName, packagePriority); @@ -133,7 +119,7 @@ namespace YooAsset /// 包裹名称 public static ResourcePackage GetPackage(string packageName) { - CheckException(packageName); + EnsureInitialized(packageName); var package = GetPackageInternal(packageName); if (package == null) YooLogger.Error($"Can not found resource package : {packageName}"); @@ -146,16 +132,16 @@ namespace YooAsset /// 包裹名称 public static ResourcePackage TryGetPackage(string packageName) { - CheckException(packageName); + EnsureInitialized(packageName); return GetPackageInternal(packageName); } /// /// 获取所有资源包裹 /// - public static List GetAllPackages() + public static IReadOnlyList GetAllPackages() { - return _packages.ToList(); + return _packages.Values.ToList(); } /// @@ -164,35 +150,24 @@ namespace YooAsset /// 包裹名称 public static bool RemovePackage(string packageName) { - CheckException(packageName); + EnsureInitialized(packageName); ResourcePackage package = GetPackageInternal(packageName); if (package == null) + { + YooLogger.Error($"Can not found resource package : {packageName}"); return false; + } - return RemovePackage(package); - } - - /// - /// 移除资源包裹 - /// - /// 包裹实例对象 - public static bool RemovePackage(ResourcePackage package) - { - CheckException(package); - string packageName = package.PackageName; if (package.InitializeStatus != EOperationStatus.None) { YooLogger.Error($"The resource package {packageName} has not been destroyed, please call the method {nameof(ResourcePackage.DestroyPackageAsync)} to destroy!"); return false; } - YooLogger.Log($"Remove resource package : {packageName}"); - // 先销毁调度器,再移除包裹 OperationSystem.DestroyPackageScheduler(packageName); - _packages.Remove(package); - return true; + return _packages.Remove(packageName); } /// @@ -201,35 +176,23 @@ namespace YooAsset /// 包裹名称 public static bool ContainsPackage(string packageName) { - CheckException(packageName); + EnsureInitialized(packageName); var package = GetPackageInternal(packageName); return package != null; } private static ResourcePackage GetPackageInternal(string packageName) { - foreach (var package in _packages) - { - if (package.PackageName == packageName) - return package; - } - return null; + _packages.TryGetValue(packageName, out var package); + return package; } - private static void CheckException(string packageName) + private static void EnsureInitialized(string packageName) { - if (_isInitialize == false) - throw new YooInitializeException($"{nameof(YooAssets)} not initialized ! Please call {nameof(YooAssets.Initialize)} first."); + if (_isInitialized == false) + throw new YooInitializeException($"YooAssets not initialized! Please call {nameof(YooAssets.Initialize)} first."); if (string.IsNullOrEmpty(packageName)) - throw new YooInitializeException("Package name cannot be null or empty !"); - } - private static void CheckException(ResourcePackage package) - { - if (_isInitialize == false) - throw new YooInitializeException($"{nameof(YooAssets)} not initialized ! Please call {nameof(YooAssets.Initialize)} first."); - - if (package == null) - throw new YooInitializeException("Package instance cannot be null !"); + throw new YooInitializeException("Package name cannot be null or empty!"); } #region 系统参数 @@ -248,9 +211,9 @@ namespace YooAsset DebugReport report = new DebugReport(); report.FrameCount = Time.frameCount; - foreach (var package in _packages) + foreach (var kv in _packages) { - var packageData = package.GetDebugPackageData(); + var packageData = kv.Value.GetDebugPackageData(); report.PackageDatas.Add(packageData); } return report; diff --git a/Assets/YooAsset/Samples~/Extension Sample/Runtime/ExtensionOperation/LoadGameObjectOperation.cs b/Assets/YooAsset/Samples~/Extension Sample/Runtime/ExtensionOperation/LoadGameObjectOperation.cs index 21bb2ef5..e1984113 100644 --- a/Assets/YooAsset/Samples~/Extension Sample/Runtime/ExtensionOperation/LoadGameObjectOperation.cs +++ b/Assets/YooAsset/Samples~/Extension Sample/Runtime/ExtensionOperation/LoadGameObjectOperation.cs @@ -9,7 +9,7 @@ public static class YooAssetsExtension public static LoadGameObjectOperation LoadGameObjectAsync(this ResourcePackage package, string location, Vector3 position, Quaternion rotation, Transform parent, bool destroyGoOnRelease = false) { var operation = new LoadGameObjectOperation(package.PackageName, location, position, rotation, parent, destroyGoOnRelease); - OperationSystem.StartOperation(OperationSystem.GLOBAL_SCHEDULER_NAME, operation); + OperationSystem.StartOperation(OperationSystem.GlobalSchedulerName, operation); return operation; } } diff --git a/Assets/YooAsset/Samples~/Extension Sample/Runtime/ExtensionOperation/OperationHelper.cs b/Assets/YooAsset/Samples~/Extension Sample/Runtime/ExtensionOperation/OperationHelper.cs index 36b77b13..d5bacbf2 100644 --- a/Assets/YooAsset/Samples~/Extension Sample/Runtime/ExtensionOperation/OperationHelper.cs +++ b/Assets/YooAsset/Samples~/Extension Sample/Runtime/ExtensionOperation/OperationHelper.cs @@ -11,6 +11,6 @@ public class OperationHelper /// public static void StartOperation(AsyncOperationBase operation) { - OperationSystem.StartOperation(OperationSystem.GLOBAL_SCHEDULER_NAME, operation); + OperationSystem.StartOperation(OperationSystem.GlobalSchedulerName, operation); } } \ No newline at end of file