Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question How to get asset references in code?

Discussion in 'Addressables' started by madGlory, Jan 19, 2021.

  1. madGlory

    madGlory

    Joined:
    Jan 12, 2016
    Posts:
    44
    So I just did the basic hello world on addressables and am able to load assets using asset references in the inspector.

    I am wondering if there is a way to easily access these addressables through code without going through the inspector. Something like this:

    Code (CSharp):
    1. AssetReference ar = AssetReferences.SOME_ADDRESSABLE;
    Is there an architecture like this that is built in or easy to set up that can work in build?
     
  2. lyha

    lyha

    Joined:
    Feb 28, 2016
    Posts:
    15
    How about using the name of the resource?
    Code (CSharp):
    1. var resourceReference = new AssetReferenceT<Texture2D>("Assets/Textures/MyTexture.png");
     
  3. madGlory

    madGlory

    Joined:
    Jan 12, 2016
    Posts:
    44
    We were hoping to avoid using naked strings or ints as they can be difficult to work with.

    We ended up building a solution that would automatically generate an enum entry for every asset in a folder and then add them to a dictionary. That way all the asset have an easy human understandable and autocomplete friendly way to reference in code.

    We also used an auto importer to automatically import the assets into the addressables groups.