Search code examples
c#unity-game-enginedotween

How to pass an argument to OnComplete in DoTween for Unity


In Unity, I want to have a DoTween animation and to execute a command in OnComplete, using as argument a variable value at animation launch time, not at OnComplete time. In the example below, I need in OnComplete the value of 0 (value of val at animation launch), not 1 (value of val at OnComplete launch):

Int val = 0;
Debug.Log("Value = " + val); // Returns 0 -> Good
transform.DOScaleY(2.0f, 1.0f).OnComplete(() =>
{
     Debug.Log("Value = " + val); // Returns 1 -> Not Good, I need 0
});
val++;

Solution

  • The reason you're seeing this is because closures refer to variables by reference, not by value. Because of this, by the time your OnComplete callback is executed, val has already been incremented, because the callback will use the latest value of whatever variable you're using. So, you can try creating a separate value to store the value of val at the time which it contains the value you're expecting:

    int val = 0;
    int currentVal = val;
    Debug.Log("Value = " + val);
    transform.DOScaleY(2.0f, 1.0f).OnComplete(() =>
    {
         Debug.Log("Value = " + currentVal);
    });
    val++;