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 xXGrime · Aug 17, 2015 at 08:09 PM · loopforeach

Onclick inside foreach loop only returns last iteration

I am instantiating buttons inside a foreach loop that represent the rooms available but when i try to add a onclick listener every button gets the last iterations onclick. Not sure why this is happening and could use some help understanding whats going on here. All of the other code works just fine its only the onclick code that is giving me issues.

 using UnityEngine;
 using System.Collections;
 using UnityEngine.UI;
 
 public class RoomList : MonoBehaviour {
     private GameObject roomButton;
     private Button b;
     public Text [] t; //Holds all texts in the gameobject roomButton and stores them in a array
     private Text roomNameText;
     private Text gamemodeText;
     private Text playerCountText;
     private int roomAmount = 0;
     private bool roomsLoaded = false;
     
 
     
     public void JoinRoom()
     {
         PhotonNetwork.JoinRoom (roomNameText.text);
     }
     
     public void OnReceivedRoomListUpdate()
     {
         foreach (RoomInfo room in PhotonNetwork.GetRoomList()) 
         {
             roomAmount++;
 
             if(roomsLoaded == false)
             {
                 roomButton = Instantiate (Resources.Load ("_Prefabs/RoomButton") as GameObject);
                 roomButton.transform.SetParent(GameObject.FindObjectOfType<Canvas>().gameObject.transform, false);
                 b = roomButton.gameObject.GetComponentInChildren <Button> ();
                 //Get all texts in roomButton and store them in t
                 t = roomButton.gameObject.GetComponentsInChildren <Text> ();
                 
                 roomNameText = t [0];
                 gamemodeText = t [1];
                 playerCountText = t [2];
                 
                 roomNameText.text = room.name;
                 gamemodeText.text = "Empty";
                 playerCountText.text = room.playerCount + "/" + room.maxPlayers;
                 
                 b.onClick.AddListener(JoinRoom);
                     
                 for(int i = 1; i < roomAmount; i++)
                 {
                     roomButton.transform.position = new Vector3(roomButton.transform.position.x, roomButton.transform.position.y - 54, roomButton.transform.position.z);
                 }
             }
         }
 
         roomsLoaded = true;
     }
 }
 

   

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

4 Replies

· Add your reply
  • Sort: 
avatar image
1

Answer by cjdev · Aug 18, 2015 at 10:32 AM

In this line:

 roomNameText.text = room.name;

you're assigning the room's name to your variable. When the loop is finished the name from the last iteration is the one the variable has when the onClick listener uses it to call the JoinRoom method.

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

Answer by Lord-Megabite · Feb 14, 2016 at 02:01 AM

I solved the problem in this moment. If you have for example a for loop and you need to pass the iteration to the AddListener, only you have to do is..

     for (int i = 0; i < totalChilds; i++) {
     
        int a = i;
     
       //....
       trigger.AddListener((idChild) => { tester(a); });
       //...
     
     }


This solve the "last iteration issue"

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

Answer by NeverHopeless · Aug 18, 2015 at 11:42 AM

You are keep updating the element roomNameText in a loop. So, probably when it is trying to join the value gets update through FOR loop.

Try changing JoinRoom function like this:

  public void JoinRoom(string roomName)
  {
      PhotonNetwork.JoinRoom (roomName);
  }

and use it like:

  b.onClick.AddListener(JoinRoom(t[0].text));

This way you don't have a dependency on a single variable.

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

Answer by Jardich · Sep 28, 2016 at 03:06 PM

It has been pointed out by others, but I wanted to mention that this is a well known gotcha on C# as described on this article:

https://blogs.msdn.microsoft.com/ericlippert/2009/11/12/closing-over-the-loop-variable-considered-harmful/

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 landon912 · Sep 28, 2016 at 03:08 PM 0
Share

It's important to note that this behavior has changed in C# 5. Once Unity updates, this behavior will change again back to what this user expects.

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

6 People are following this question.

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

Related Questions

Foreach with GameObject.Find() 1 Answer

foreach loop problem 1 Answer

my foreach loop and condition wont work 0 Answers

Logic question, unique path finding system 2 Answers

Instantiate inside foreach loop 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