'await' in for loop doesn't works properly

I want to run the await syntax when the value of i is 1 or higher, and run the for loop under it.

But when I run it, if code encounter await syntax when i is 1 or higher, then i initializes to 0 and then executes the syntax below.
For example, if i traverses from 0 to 3, the value of i in turn does not change from 0 to 3, but instead operates like 0, 0-1, 0-1-2, 0-1-2-3. My intention is to operate in the order of 0-1-2-3.

Can you tell me why and how to solve it?

This is my code:

async void ApplyBlendShape()
{
    if(skinnedMeshRenderer != null)
    {
        blendListCount = blendList.Count;
        blendShapeCount = skinnedMesh.blendShapeCount;

        Debug.Log($"### blendListCount : {blendListCount} ###");

        for(int i = 0; i < blendListCount; i++)
        {
            Debug.Log($"### i : {i} ###");

            if(i > 0)
            {
                await Task.Run(() => Wait().AttachExternalCancellation(this.cancelToken));
            }

            for(int j = 0; j < blendShapeCount; j++)
            {
                Debug.Log($"### j : {j} ###");
                currentBlendShapeValue = skinnedMeshRenderer.GetBlendShapeWeight(j);
                nextBlendShapeValue = blendList[i].ElementAt(j).Value;
                skinnedMeshRenderer.SetBlendShapeWeight(j, Mathf.Lerp(currentBlendShapeValue, nextBlendShapeValue, blendSpeed * Time.deltaTime));
            }
        } 
    }
}
static async UniTask Wait()
{
    try
    {
        await UniTask.Delay(300);
        Debug.Log("Wait Done");
    }
    catch(System.Exception ex)
    {
        Debug.LogError("An error occurred : " + ex.Message);
    }
}

2 Answers

2

You can try index = i and use “index” instead “i”.

for(int i = 0; i < blendListCount; i++)
        {
            Debug.Log($"### i : {i} ###");
            int index = i;
            if(i > 0)
            {
                await Task.Run(() => Wait().AttachExternalCancellation(this.cancelToken));
            }

            for(int j = 0; j < blendShapeCount; j++)
            {
                nextBlendShapeValue = blendList[index].ElementAt(j).Value; 
            }
        } 

Why are you doing a nested for loop? Why not just one for loop, you only want to loop over the array once.