Is it possible to pass parameter to .Completed function?

Something like this:

Addressables.InstantiateAsync("Assets/0 Addressables/Prefabs/Sprite.prefab").Completed += CompletedInstantiateInventory("string param");

ive been trying to do this for a while but I always get one error or another. I need to pass parameter there

You don’t need to pass a parameter since C# supports variable closures in anonymous functions. Just use whatever you need inside the callback and the compiler will take care of the rest.
Of course, there’s extra GC associated with closures, but I don’t think the addressables team is worried about that when it pales in comparison to a full asset load.

im sorry but i dont understand you. “variable closures in anonymous functions” what?

A quick google search (for C# closure variable capture) revealed lots of results. Give this a read: The Beauty of Closures

While I was using closure variable capture in anonymously functions for months, I am trying to simplified my code by using one method with switch cases by giving parameters passed from AssetReference.Completed action. Is this plausible?

I’m not sure what you mean, could you provide some pseudo code to illustrate your idea?

I figured out that if I wanna pass one more parameter with .Completed has to be Action<T,T1>. But it doesn’t.

To make my code cleaner, I wanna do the following.

enum LoadType : short
{
    Download,
    Load,
    Instantiate,
}

void downlaod(string scene)
{
    DownloadDependenciesAsync().Completed += OnCompleted;
    StartCoroutine(CalculatePercent(handle, LoadType.Download));
}

void load(string scene)
{
    LoadSceneAsync().Completed += OnCompleted;
    StartCoroutine(CalculatePercent(handle, LoadType.Load));
}

The following can’t be compiled since .Completed is Action<T> instead of Action<T,T1>.

void OnCompleted(AsyncOperationHandle handle, LoadType type)
{
    StopCoroutine(CalPercent(handle, type));
    doThings();
    if (type == LoadType.Downlaod)
        load(scene);
    else if (type == LoadType.Load && --SceneCountDown == 0)
        SceneManager.UnloadSceneAsync(SceneManager.GetActiveScene(), options: UnloadSceneOptions.None);
}

So, using closure variable capture is more plausible. Or implement a new .Completed Action.

1 Like

So for your example, you could just do the OnCompleted at the end of your Coroutine. But if you want to use the callback, you would have to use a lambda(anonymous function) to do it:

DownloadDependenciesAsync().Completed += handle => OnCompleted(handle, LoadType.Download);
9 Likes