Search Unity

AssetReference by Component Type

Discussion in 'Addressables' started by CDF, Aug 16, 2019.

  1. CDF

    CDF

    Joined:
    Sep 14, 2013
    Posts:
    1,311
    Hey, is there already a solution for using an AssetReference bound to a Component type?
    I want to be able to reference an AddressableAsset by a Component and only show those Components in the AssetReference popup.

    I've come up with this which seems to work ok. Just wondering if something else already exists?

    Code (CSharp):
    1. [Serializable]
    2. public class AssetReferenceCustomComponent : AssetReferenceComponent<CustomComponent> {
    3.  
    4.     public AssetReferenceCustomComponent(string guid) : base(guid) {
    5.     }
    6. }
    7.  
    8. public abstract class AssetReferenceComponent<TComponent> : AssetReferenceT<TComponent> {
    9.  
    10.     public AssetReferenceComponent(string guid) : base(guid) {
    11.     }
    12.  
    13.     public override bool ValidateAsset(Object obj) {
    14.  
    15.         var type = obj.GetType();
    16.  
    17.         if (typeof(TComponent).IsAssignableFrom(type)) {
    18.  
    19.             return true;
    20.         }
    21.  
    22.         GameObject gameObject = (obj as GameObject);
    23.  
    24.         return gameObject ? gameObject.GetComponent<TComponent>() != null : false;
    25.     }
    26.  
    27.     public override bool ValidateAsset(string path) {
    28.  
    29. #if UNITY_EDITOR
    30.         var type = UnityEditor.AssetDatabase.GetMainAssetTypeAtPath(path);
    31.  
    32.         if (typeof(TComponent).IsAssignableFrom(type)) {
    33.  
    34.             return true;
    35.         }
    36.  
    37.         GameObject gameObject = UnityEditor.AssetDatabase.LoadAssetAtPath<GameObject>(path);
    38.  
    39.         return gameObject ? gameObject.GetComponent<TComponent>() != null : false;
    40. #else
    41.         return false;
    42. #endif
    43.     }
    44. }
     
  2. unity_bill

    unity_bill

    Joined:
    Apr 11, 2017
    Posts:
    1,053
  3. RunninglVlan

    RunninglVlan

    Joined:
    Nov 6, 2018
    Posts:
    182
    @unity_bill, will ComponentReference functionality come to the Addressables package?