Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

How to check if an asset exists with given key

Discussion in 'Addressables' started by Deleted User, Jul 9, 2019.

Thread Status:
Not open for further replies.
  1. Deleted User

    Deleted User

    Guest

    I want to check if an asset exists or not before calling Instantiate method.
     
  2. Favo-Yang

    Favo-Yang

    Joined:
    Apr 4, 2011
    Posts:
    464
    Addressables.LoadResourceLocationsAsync(address, type), then check the if the location exists.
     
  3. Deleted User

    Deleted User

    Guest

    This method also prints error when the address doesn't exist.
    I need a silent method that just returns a status of an asset.
     
  4. Favo-Yang

    Favo-Yang

    Joined:
    Apr 4, 2011
    Posts:
    464
    Then it is a bug. Could submit a bug report to Unity?
     
  5. unity_bill

    unity_bill

    Joined:
    Apr 11, 2017
    Posts:
    1,053
    This is definitely a bug. It would seem that we had a partial fix for this, and simply didn't deliver. We will get to to fixing this.
     
    xifeng8445 likes this.
  6. RobbyZ

    RobbyZ

    Joined:
    Apr 17, 2015
    Posts:
    38
    I am currently doing this via the below technique, but it is inefficient and only works in editor. It seems like a simple 'hasAddress' method should exist for this somewhere.

    Code (CSharp):
    1. public static bool DoesAddressExist(AddressableAssetSettings settings, string testAddress)
    2. {
    3.     List<AddressableAssetEntry> allEntries = new List<AddressableAssetEntry>();
    4.     settings.GetAllAssets(allEntries);
    5.    
    6.     foreach (AddressableAssetEntry entry in allEntries)
    7.     {
    8.         if (entry.address == testAddress)
    9.             return true;
    10.     }
    11.  
    12.     return false;
    13. }
     
    illusory and Raghavendra like this.
  7. chanon81

    chanon81

    Joined:
    Oct 6, 2015
    Posts:
    168
    Here is how I do it.

    Code (CSharp):
    1.  
    2.         public static bool AssetExists(object key) {
    3.             if (Application.isPlaying) {
    4.                 foreach (var l in Addressables.ResourceLocators) {
    5.                     IList<IResourceLocation> locs;
    6.                     if (l.Locate(key, null, out locs))
    7.                         return true;
    8.                 }
    9.                 return false;
    10.             }
    11.             else if (Application.isEditor && !Application.isPlaying) {
    12. #if UNITY_EDITOR
    13.                 // note: my keys are always asset file paths
    14.                 return FileExists(System.IO.Path.Combine(Application.dataPath, (string)key));
    15. #endif
    16.             }
    17.             return false;
    18.         }
    19.  
    Addressables must have been initialized (Addressables.InitializeAsync() must have completed.)

    Then you can do a simple sync call of AssetExists(myAssetPathToCheck)

    This still works in 1.1.7
    It is very convenient because you can just await for Addressables.InitializeAsync() once when you start your game, and then can always do the sync AssetExists call.

    I don't know why Addressable devs don't provide something simple like this for such a basic and highly needed requirement.

    Just to check whether an asset exists they want you to do an async call.

    I use AssetExists for "convention over configuration" style code, where, for example, the game checks if an image exists or not and if it doesn't then uses the default image. Being able to do it in a sync call greatly reduces the code complexity and helps with perceived performance.
     
  8. unity_bill

    unity_bill

    Joined:
    Apr 11, 2017
    Posts:
    1,053
    You answered your own question. We do that so it can be called at any time (even before init is done), and will give you a correct result when ready.

    fixed in 1.1.7
     
  9. DigitalContinueChar

    DigitalContinueChar

    Joined:
    May 21, 2019
    Posts:
    1
    For all those coming in the future, this method seems to be deprecated, as the ResourceLocators don't seem to support Locate anymore.

     
  10. chanon81

    chanon81

    Joined:
    Oct 6, 2015
    Posts:
    168
    Hmm... I'm still using it just fine in 1.4.0.

    And to answer unity_bill .. the advantage of my method is you can await Addressables.InitializeAsync() once in the initial loading screen of your game. (Addressables Initialize only once anyways.) Then you can use my AssetExists method synchronously anywhere afterwards.

    While if you use the built-in method, then you will have to do an async call every time you want to just check if an asset exists .. which many times are in places that can't or you don't want to use async cause it will complicate your code a lot more.
     
    Jaimi likes this.
  11. caochao88_unity

    caochao88_unity

    Joined:
    May 16, 2019
    Posts:
    26
    maybe you should try async/await:
    Code (CSharp):
    1. var list = await Addressables.LoadResourceLocationsAsync(assetId).Task;
    2.             if (list != null && list.Count > 0)
    3.             {
    4.             }
     
  12. caochao88_unity

    caochao88_unity

    Joined:
    May 16, 2019
    Posts:
    26
    do I need release the AsyncOperationHandle returned by LoadResourceLocationsAsync?
     
    Last edited: Mar 2, 2020
  13. chanon81

    chanon81

    Joined:
    Oct 6, 2015
    Posts:
    168
    I know that async/await can be used. I use async/await throughout my code where needed. The point of my code above is that just to check whether an asset at a path exists I don't want to have to use async/await.
     
    skwsk8 likes this.
  14. caochao88_unity

    caochao88_unity

    Joined:
    May 16, 2019
    Posts:
    26
    Code (CSharp):
    1. var list = await Addressables.LoadResourceLocationsAsync(assetAddr).Task;        
    2. if (list != null && list.Count > 0)        
    3. {
    4. //assetAddr is existed in Addressable Groups
    5. }
    I think this codes is as easy as sync mode codes.
     
    Last edited: Mar 2, 2020
  15. chanon81

    chanon81

    Joined:
    Oct 6, 2015
    Posts:
    168
    There many places in code where it isn't convenient to use async, such as property getters/setters.

    Anyways, we can agree to disagree. I am just explaining my reasons.
     
    Jaimi, skwsk8 and Julien-Lynge like this.
  16. FlightOfOne

    FlightOfOne

    Joined:
    Aug 1, 2014
    Posts:
    668
    Thank you VERY MUCH for doing this!!

    @unity_bill This should at least be mentioned in the documentation as an example, if it wasn't for this answer, I'd be spending so much time figuring this out. Speaking of documentations, there is definitely more questions than answers out there. I really hope there's more info and tutorials on this subject because so far I am truly amazed by how helpful addressables are going to be on my project. I can see a lot of people steering away from this because its hard to find things and miss out.
     
    Last edited: Sep 16, 2020
    chanon81 likes this.
  17. unity_bill

    unity_bill

    Joined:
    Apr 11, 2017
    Posts:
    1,053
  18. lyflike

    lyflike

    Joined:
    Dec 23, 2018
    Posts:
    12
    Please help!
    How can i access .dat file from s3 as addressable ?

    public void LoadAddressableComponentTextAssets(string name, Action<TextAsset> OnLoad, Action OnFail) {
    ResultTextAsset = OnLoad;

    try {
    Addressables.LoadAssetAsync<TextAsset>(name).Completed += OnLoadDone;
    }
    catch (Exception e) {
    OnFail?.Invoke();
    }
    }

    private void OnLoadDone(AsyncOperationHandle<TextAsset> obj) {
    Debug.Log(obj.Result.name);
    ResultTextAsset?.Invoke(obj.Result);
    }

    Error :
    Exception encountered in operation UnityEngine.ResourceManagement.ResourceManager+CompletedOperation`1[UnityEngine.TextAsset], result='', status='Failed': Exception of type 'UnityEngine.AddressableAssets.InvalidKeyException' was thrown., Key=Shirt_1_00_26, Type=UnityEngine.TextAsset
     
Thread Status:
Not open for further replies.