How to Unload Assets When not Needed

I have many images to display on UI that I’m handling with addressable. Here is the code I use (error handling is stripped):

public class ImageLoader : Monobehaviour
{
    public AssetReference ImageAsset;

    private void OnEnable()
    {
        StartCoroutine(loadImage());
    }

    IEnumerator loadImage()
    {
        yield return ImageAsset.LoadAssetAsync<Sprite>();
        GetComponent<Image>().sprite = (Sprite)ImageAsset.Asset;
    }

    private void OnDisable()
    {
        GetComponent<Image>.sprite = null;
        ImageAsset.ReleaseAsset();
    }
}

It loads the sprite into the Image when the GameObject is enabled, and clears it when GameObject is disabled. However, when I check the profiler window, the asset is loaded into memory but not unloaded when GameObject is disabled. When I load a different scene the asset is unloaded from memory. What am I doing wrong?

The last section in the addressables memory management should explain this: Memory management | Addressables | 1.3.8

Basically, the asset isn’t cleared from memory unless everything in its bundle has been released, or you call Resources.UnloadUnusedAssets.

I didn’t know that before. Thank you! Although it doesn’t seem to solve my specific problem. The doc seem to imply when ref-count is 0 the asset might not be unloaded yet. I just checked my profiler and the ref-count did not drop to 0. It says that it’s referenced by (Sprite), but when I try to find references in scene it finds nothing. When I click on the reference it just highlights my asset in the project window. From the Hierarchy window I can also see that the Image sprite is emptied.

That may be an Editor behavior. Memory behaves differently in the Editor and some Editor bits may be holding on to the sprite or atlas, including inspector views of the Asset. Did you check that behavior in a build yet?

I was just doing that before I see your post! And yes you are correct, it is an Editor behavior.