- Home /
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;
}
}
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.
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"
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.
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:
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
![](https://koobas.hobune.stream/wayback/20220612000222im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
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