Jump to content
  • Advertisement
Sign in to follow this  
kitman20022002

Unity Question about lambda function

This topic is 983 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

In my C# unity5 code I got this 

CityButton cb = go.AddComponent<CityButton>();

b.onClick.AddListener (() => {cb.CheckShouldExpand(b);});

 

my question is

why this part works "() => {cb.CheckShouldExpand(b);}" 

but this "(cb, b) => cb.CheckShouldExpand(b);" OR "(b) => cb.CheckShouldExpand(b);" does not ? 

 

because what I understand from the internet MSDN and dotnetperls.com says

() : input parameters

=> goesto

cb.CheckShouldExpand(b) : expression

 

which means from my understanding the expression part(Right) cb and b doesn't know what it is until you pass it in from the input parameters(Left). 

Share this post


Link to post
Share on other sites
Advertisement

What you might be asking about is how "b" and "cb" are working in the lambda. This is called "capturing", the city button and "b" variables are captured when the lambda is created, and are available when the lambda is executed later.

 

See Variable Scope in Lambda Expressions.

Share this post


Link to post
Share on other sites

And also just to clarify,

 


but this "(cb, b) => cb.CheckShouldExpand(b);" OR "(b) => cb.CheckShouldExpand(b);" does not ? 

 

Those don't work because the delegate must be a nullary function (not take any parameters) so you can bind neither unary nor binary lambdas; the event doesn't know what to pass in as the parameters even if you could bind such a delegate.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!