Use Task to wait for AssetDatabase.ImportPackage to execute

Original link: https://blog.853lab.com/2022/07/post_2583.html

 public static async Task ImportPackageAsync(string packagePath) { TaskCompletionSource<object> taskCompletionSource = new TaskCompletionSource<object>(); try { AssetDatabase.importPackageCancelled += OnImportPackageCancelled; AssetDatabase.importPackageCompleted += OnImportPackageCompleted; AssetDatabase.importPackageFailed += OnImportPackageFailed; AssetDatabase.ImportPackage(packagePath, false); await taskCompletionSource.Task; } catch (System.Exception exception) { Debug.LogException(exception); } finally { AssetDatabase.importPackageCancelled -= OnImportPackageCancelled; AssetDatabase.importPackageCompleted -= OnImportPackageCompleted; AssetDatabase.importPackageFailed -= OnImportPackageFailed; } void OnImportPackageCancelled(string packageName) { taskCompletionSource.SetCanceled(); } void OnImportPackageCompleted(string packageName) { taskCompletionSource.SetResult(null); } void OnImportPackageFailed(string packageName, string errorMessage) { taskCompletionSource.SetException(new System.Exception(errorMessage)); } }

Code reference to Github: YLahin/TequilaLegacy/YL.Wrench.Unity.Editor/UnityPackageImporter.cs

This article is reproduced from: https://blog.853lab.com/2022/07/post_2583.html
This site is for inclusion only, and the copyright belongs to the original author.

Leave a Comment