Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
12 Jun 22 - 14 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
  • Help Room /
avatar image
4
Question by sokolman · Jan 04, 2016 at 08:50 PM · prefabbuttonsprefab-instance

How to AddListener() (from code) featuring an argument for multiple buttons?

Hi ! I have some problem with loading prefab and with that loading add listners for my prefab. The prefab have 4 buttons. Here's code that I use:

GameObject go = (GameObject)Instantiate(Resources.Load("Prefab"));

     Button[] buttons = go.GetComponentsInChildren<Button>();

     for (int i = 0; i < buttons.Length; i++)
     {
         buttons[i].onClick.AddListener(() => { eventManager.answerSelection(i); });
     }

eventMangaer Is my script with button logic.

My problem is that when I click buttons, there is execption with index 4 at all buttons.

Comment
Comments Locked
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

1 Reply

· Add your reply
  • Sort: 
avatar image
28
Best Answer

Answer by cjdev · Jan 05, 2016 at 02:17 AM

What's happening is that when you create a lambda expression (a delegate, which is what the event listener is) and you "capture" or include an outside variable you are actually including a pointer to that variable's location in memory. In other words, everything you do to the original, outside variable will be reflected in the logic inside the lambda expression. Practically speaking, to get around this you can instantiate a temp variable in your for loop like this:

 Button[] buttons = go.GetComponentsInChildren<Button>();
 for (int i = 0; i < buttons.Length; i++)
 {
      int temp = i
      buttons[i].onClick.AddListener(() => { eventManager.answerSelection(temp); });
 }

This way you are creating a temporary variable whose only outside scope is the one iteration of the for loop and so you can use it without fear of accidental external modification.

Comment
Comments Locked · Show 7 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image sokolman · Jan 05, 2016 at 06:29 AM 0
Share

Thanks, i miss that !

avatar image SecondBake · Jun 19, 2016 at 06:58 PM 0
Share

Had the same issue. Thanks for the tip!

avatar image Northmaen · Oct 25, 2016 at 02:48 PM 0
Share

Thanks, you saved my day !

avatar image DerDicke · Feb 16, 2017 at 12:44 PM 0
Share

Thanks man. That cost me half a day. Will google for a way to avoid lambda expressions at all cost!

avatar image WalkieStalkie · Aug 06, 2017 at 12:19 AM 0
Share

Thanks! that saved me a lot of time

Show more comments

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

48 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Another another **Setting the parent of a transform which resides in a prefab** problem, and OnValidate 1 Answer

How to designate a specific prefab for the script. (Or how to move something to a specific prefab) 1 Answer

How to detect if any prefab is instantiated in the scene from a script? 2 Answers

After being instantiated once and then destroyed, prefab is null 0 Answers

Problems with instantiating 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges