Anonymous Functions – Closure Callbacks

Here is an example of anonymous functions in unity, below is a very helpful technique around loading assets and then setting a delegate to grab that loaded asset. Below, take note of the ‘closure’ delegate, which is being passed into the asset bundle manager load function as the second parameter. Because the delegate was defined inside the loop it forms closure around the variable ‘i’ which would usually not exist. When each bundle is loaded the callback will trigger and the asset will be placed at the correct index in the array.


for(int i=0; i < things.Length; i++)
{
    AssetBundleManager.Load(thingNames[i], delegate (AssetBundle bundle)
    {
        characters[i] = bundle.Load(thingNames[i] + "LOD0")
    });
}

Leave a Reply

Your email address will not be published. Required fields are marked *