using UnityEngine; using UnityEngine.AddressableAssets; using UnityEngine.ResourceManagement.AsyncOperations; #if UNITY_EDITOR using UnityEditor; #endif /// /// Creates an AssetReference that is restricted to having a specific Component. /// * This is the class that inherits from AssetReference. It is generic and does not specify which Components it might care about. A concrete child of this class is required for serialization to work. /// * At edit-time it validates that the asset set on it is a GameObject with the required Component. /// * At runtime it can load/instantiate the GameObject, then return the desired component. API matches base class (LoadAssetAsync & InstantiateAsync). /// /// The component type. public class ComponentReference : AssetReference { /// public ComponentReference(string guid) : base(guid) { } /// public new AsyncOperationHandle InstantiateAsync(Vector3 position, Quaternion rotation, Transform parent = null) { return Addressables.ResourceManager.CreateChainOperation(base.InstantiateAsync(position, Quaternion.identity, parent), GameObjectReady); } /// public new AsyncOperationHandle InstantiateAsync(Transform parent = null, bool instantiateInWorldSpace = false) { return Addressables.ResourceManager.CreateChainOperation(base.InstantiateAsync(parent, instantiateInWorldSpace), GameObjectReady); } /// public AsyncOperationHandle LoadAssetAsync() { return Addressables.ResourceManager.CreateChainOperation(base.LoadAssetAsync(), GameObjectReady); } /// AsyncOperationHandle GameObjectReady(AsyncOperationHandle arg) { var comp = arg.Result.GetComponent(); return Addressables.ResourceManager.CreateCompletedOperation(comp, string.Empty); } /// /// Validates that the assigned asset has the component type /// /// /// public override bool ValidateAsset(Object obj) { var go = obj as GameObject; return go != null && go.GetComponent() != null; } /// /// Validates that the assigned asset has the component type, but only in the Editor /// /// /// public override bool ValidateAsset(string path) { #if UNITY_EDITOR //this load can be expensive... var go = AssetDatabase.LoadAssetAtPath(path); return go != null && go.GetComponent() != null; #else return false; #endif } /// public void ReleaseInstance(AsyncOperationHandle op) { // Release the instance var component = op.Result as Component; if (component != null) { Addressables.ReleaseInstance(component.gameObject); } // Release the handle Addressables.Release(op); } }