cowlinator
cowlinator

Reputation: 8813

How to watch (i.e. debug) extra-lambda variable inside lambda scope in C#/Visual-Studio/Unity3d?

When using Visual Studio Professional 2015 with Unity, I've noticed that when I am stepping though the body of a lambda expression, I cannot watch variables which were declared/assigned outside of but are being read inside of the lambda expression.

    private IEnumerator DoTheThing(string filter)
    {
        TextureDownload texDl = new TextureDownload();
        texDl.OnCompleted += () =>
        {
            _log.Log("Mesh texture " + texDl.GetType() + ":" + texDl.GetHashCode());
            textures.Add(texDl);
        };
        yield break;
    }

I get the error

The identifier texDl is not in the scope

Obviously the variable is accessible in this scope, because the lambda function is using it.

Is there any remotely easy/convenient way to watch the value of such variables?

Upvotes: 1

Views: 843

Answers (1)

cowlinator
cowlinator

Reputation: 8813

Turns out this is a variation of C# lambda call in for loop references to last object

There is an issue with Mono/Unity with coroutines and lambda expressions;

The coroutine itself is an implicit closure as well which moves all local variable to a seperate class as member variables. That means it's impossible to create a "real" local variable inside a generator method. That's why the explicit local variable declaration doesn't work.

See http://answers.unity3d.com/questions/974036/c-lambda-call-in-for-loop-references-to-last-objec.html

Upvotes: 2

Related Questions