Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 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
0
Question by Rodlaiz · Sep 18, 2016 at 01:43 PM · variableloopmethod

Can't pass a variable as method parameter?

OK, this is a tricky one for me...

I'm trying to add a OnClick listener to my buttons:

 int i = 0;
             foreach (var optionString in optionsCollection.options)
             {
 
                 testButtons[i].onClick.AddListener(() => SetOption(i));
           
                 i++;       
             }

But for some reason when I click the button I get this error:

ArgumentOutOfRangeException: Argument is out of range. Parameter name: index System.Collections.Generic.List`1[System.Collections.Generic.KeyValuePair`2[System.String,System.String]].get_Item (Int32 index) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Collections.Generic/List.cs:633) Yarn.VirtualMachine.m_0 (Int32 selectedOption) Yarn.Unity.PopulateUI.SetOption (Int32 selectedOption) (at Assets/Scripts/PopulateUI.cs:116) Yarn.Unity.PopulateUI+cIterator5.<>m_0 () (at Assets/Scripts/PopulateUI.cs:93) UnityEngine.Events.InvokableCall.Invoke (System.Object[] args) ...

But if I go like this:

    int i = 0;
             foreach (var optionString in optionsCollection.options)
             {
 
                 if (i == 0)
                 {
                     testButtons[i].onClick.AddListener(() => SetOption(0));
                 }else
                 {
                     testButtons[i].onClick.AddListener(() => SetOption(1));
                 }
                 i++;       
             }

...it works! My question is why I can't pas the int i as a parameter of the function SetOption? Why if I hardcode the number it works?

Thank you

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
0

Answer by NoseKills · Sep 21, 2016 at 08:04 PM

There's no "problem" with what you are doing here, except that this code works probably a bit differently than what one would easily expect.

In C#, when you write a closure like that, it is not the value of i that gets captured in the anonymous method, but it's the variable itself. This almost makes it seem like the fundamentals of value types vs. reference types gets broken.

After you finish that loop, i has the value optionsCollection.options.Count (or .Length) and whenever you finally click your buttons, all of them call SetOption with that same value.

If you want to prevent this, you have to pass to the closure an integer that you don't change anywhere later.

 int i = 0;
 foreach (var optionString in optionsCollection.options)
 {
     var temp = i;
      testButtons[i].onClick.AddListener(() => SetOption(temp));
      i++;       
 }



Comment
Add comment · Show 1 · 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 Rodlaiz · Sep 22, 2016 at 12:03 PM 0
Share

Hello @Nose$$anonymous$$ills

Thank you very much for your answer.

I've tried your solution and I don't get the error anymore :)

Still, I don't know why but it doesn't work. Both buttons are getting the same value (1, ins$$anonymous$$d of 0 and 1 each)

I don't believe is an instance problem because with the "if" solution the buttons works just fine. I've debugged the temp var before assigning it to the method and the values are correct (0 and 1)

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

4 People are following this question.

avatar image avatar image avatar image avatar image

Related Questions

Passing Parameters by Value or by Reference 2 Answers

How Reset Variable After Loop 1 Answer

How do I create a variable for each GameObject that I added to an array by using a loop? 2 Answers

ArgumentException: The Object you want to instantiate is null. 1 Answer

variables based on array.length not updating in JS 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