Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 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 /
avatar image
3
Question by ovlay · Nov 15, 2016 at 04:29 PM · runtimebuttonsmethodsdelegatesindexoutofrangeexception

Index out of range when using delegates to set onClick at runtime

I am writing a script that passes 2 arrays into a menu creation method- the arrays hold the text and the models (which the buttons spawn) for the buttons that the menu will create. However, due to the fact that I would like to make the whole thing dynamic I need to set all the references to the gameobjects at runtime.

Below is the method which sets up the panel with buttons

 public void Choice(string upgradeQuestion, /*List<UnityAction>*/ string[] upgradeText, GameObject[] buildings)
 {

     Button[] buttonList = null;
     buttonList = new Button[upgradeText.Length];
     modalPanelObject.SetActive(true);
     for (int i = 0; i < upgradeText.Length; i++)
     {
         Button newbut = Instantiate(button);
         Debug.Log(newbut);
         newbut.transform.SetParent(buttonPanel.transform);
         buttonList[i] = newbut;
         //Remove previous listeners
         buttonList[i].onClick.RemoveAllListeners();
         //Add Panelclose listener
         AddOnClickListener(buttonList[i], ClosePanel);
         //Add Custom Listener
         Debug.Log(buildings[i]);
         buttonList[i].onClick.AddListener(delegate { BuildingPlacer(buildings[i]); });
         buttonList[i].GetComponentInChildren<Text>().text = upgradeText[i];
         Debug.Log("button created");
     }

     this.question.text = upgradeQuestion;
     this.iconImage.gameObject.SetActive(false);
     foreach (Button b in buttonList)
     {
         b.gameObject.SetActive(true);
     }

 }

The problem is that

 buttonList[i].onClick.AddListener(delegate { BuildingPlacer(buildings[i]); });

returns an IndexOutOfRangeException when the buttons are clicked. The arrays are not empty and are of the same size, the buttons get created but the issue lies when the onclick is assigned.

Any idea why i am getting an index out of range

Comment
Add comment
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
7

Answer by NoseKills · Nov 15, 2016 at 04:42 PM

The whole loop is run to completion when you call this method, after that, at some point you press the button, and by then the value of i is upgradeText.Length because that's the exit condition for your loop.

When you use delegates or such in this manner, the variable i gets wrapped into the delegate rather than just its value, making it sort of act like a reference type.

It should be easily fixable by passing a variable you don't change later into the delegate.

 var i2 = i;
 buttonList[i].onClick.AddListener(delegate { BuildingPlacer(buildings[i2]); });


Comment
Add comment · Show 3 · 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 Capricornum · May 28, 2019 at 08:39 PM 0
Share

Thank you!!! I had the EXACT same problem. How did you know about that? I don't understand it at all.

$$anonymous$$y solution was to cache the needed parameter beforehand and pass it directly to the delegate, ins$$anonymous$$d of passing it using i.

avatar image Bunny83 Capricornum · May 28, 2019 at 09:54 PM 1
Share

Well, every programmer should know about closures and why closing over for loop variables is never a good idea. You may want to read Eric Lipperts post closing over the loop variable considered harmful. Eric was on the $$anonymous$$m who developed the $$anonymous$$S C# compiler.


Another reason you should know about this is because there are an endless stream of questions about that topic on SO but also here on UnityAnswers. Note that the $$anonymous$$ono C# compiler does has some additional issues when it comes to coroutines. See this question for more details. Using a local variable inside the for loop wouldn't work when the for loop is inside a coroutine because the mono compiler turns all local variables inside the coroutine into member variables of the internally created statemachine object. So creating a closure around such a variable will always close over the same variable. Using a nested lambda expression does work. Though i would generally recommend to avoid such cases. Those are the tiny bits you should know to not get caught in such issues ;)

avatar image Capricornum Bunny83 · May 29, 2019 at 07:23 AM 0
Share

Thank you very much Bunny83. This is very useful background knowledge. Also the extra bit about the coroutines.

So when you say you would generally avoid such cases, you were referring to the closure within Coroutines right? Not the closure in normal for loops?

What 'ovlay' and I are doing, i.e. assigning listeners to buttons in a for loop, that is generally okay using a local variable, isn't it?

$$anonymous$$aybe some day I will actually be able to call myself programmer, thanks to people like you!

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

61 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 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

Unity new UI. Working with scripts. 1 Answer

Export objects to a .3DS file at runtime 1 Answer

Cannot cast Method group to UnityAction 0 Answers

Are ui button multiple on click() functions possible? 1 Answer

Enable/Disable part of script with Button? 0 Answers


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