diff --git a/UnityProject/Assets/TEngine/Runtime/Extension/UnityExtension.cs b/UnityProject/Assets/TEngine/Runtime/Extension/UnityExtension.cs index dbea4fb3..46ac4590 100644 --- a/UnityProject/Assets/TEngine/Runtime/Extension/UnityExtension.cs +++ b/UnityProject/Assets/TEngine/Runtime/Extension/UnityExtension.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using Cysharp.Threading.Tasks; using UnityEngine; using UnityEngineInternal; @@ -168,11 +169,13 @@ namespace TEngine operation = null; return; } + image.sprite = operation.AssetObject as Sprite; if (isSetNativeSize) { image.SetNativeSize(); } + image.gameObject.GetOrAddComponent().Reference(operation, spriteName); }, customPackageName: customPackageName); } @@ -204,7 +207,7 @@ namespace TEngine { var operation = GameModule.Resource.LoadAssetGetOperation(spriteName, customPackageName: customPackageName); spriteRenderer.sprite = operation.AssetObject as Sprite; - + spriteRenderer.gameObject.GetOrAddComponent().Reference(operation, spriteName); } else @@ -300,5 +303,62 @@ namespace TEngine return gameObject.GetComponent(); } + + /// + /// 加载资源并绑定资源引用到GameObject上。 + /// + /// GameObject。 + /// 资源定位地址。 + /// 加载完成回调。 + /// 自定义包。 + /// 资源实例类型。 + /// 资源实例。 + public static T LoadAsset(this GameObject gameObject, string location, Action callBack = null, + string customPackageName = "") where T : UnityEngine.Object + { + if (gameObject == null) + { + return null; + } + + var operation = GameModule.Resource.LoadAssetGetOperation(location, customPackageName: customPackageName); + var asset = operation.AssetObject as T; + gameObject.GetOrAddComponent().Reference(operation, location); + callBack?.Invoke(asset); + return asset; + } + + /// + /// 异步加载资源并绑定资源引用到GameObject上。 + /// + /// GameObject。 + /// 资源定位地址。 + /// 加载完成回调。 + /// 自定义包。 + /// 资源实例类型。 + /// 资源实例。 + public static async UniTask LoadAssetAsync(this GameObject gameObject, string location, Action callBack = null, + string customPackageName = "") where T : UnityEngine.Object + { + if (gameObject == null) + { + return null; + } + + var operation = GameModule.Resource.LoadAssetAsyncHandle(location, customPackageName: customPackageName); + + bool cancelOrFailed = await operation.ToUniTask().AttachExternalCancellation(gameObject.GetCancellationTokenOnDestroy()) + .SuppressCancellationThrow(); + + if (cancelOrFailed) + { + return null; + } + + gameObject.GetOrAddComponent().Reference(operation, location); + var asset = operation.AssetObject as T; + callBack?.Invoke(asset); + return asset; + } } } \ No newline at end of file