Hi, I’m working on assigning things to buttons as seen below. Currently each button I’m trying to assign a listener to is called ServerNamePrefab 0, ServerNamePrefab 1, 2 3 etc.(though they are not actual prefabs but rather duplicates of the original).
In anycase, they’re currently set up in a UI improvised list I’ve made, and the code can be seen below.
UnityEngine.UI.Text[] GamNam = new UnityEngine.UI.Text[hostData.Length]; //sets array length of text component GamNam.
UnityEngine.UI.Button[] GamBut = new UnityEngine.UI.Button[hostData.Length];//sets array length of button component GamBut.
GameObject[] ServerName = new GameObject[hostData.Length];
HostData curhost;
for (int i = 0; i < hostData.Length; i++){
string j = i.ToString();
//UnityEngine.UI.Text[] GamNam = new UnityEngine.UI.Text[hostData.Length]; //sets array length of text component GamNam.
//UnityEngine.UI.Button[] GamBut = new UnityEngine.UI.Button[hostData.Length];//sets array length of button component GamBut.
//GameObject[] ServerName = new GameObject[hostData.Length];
//HostData curhost;
//finds GameObject of name "ServerNamePrefab i"(though it isnt really a prefab)
ServerName *= GameObject.Find ("ServerNamePrefab " + j);*
_ ServerName*.SetActive(true);*_
* //finds button text to set gameroomname.*
GamNam = ServerName*.GetComponentInChildren<UnityEngine.UI.Text>();*
GamNam_.text = hostData*.gameName;
Debug.Log (hostData.gameName);
//debugs the correct name for that hostData.*_
_ curhost = hostData*;*_
GamBut = ServerName*.GetComponent<UnityEngine.UI.Button>(); // is a button component of ServerName GameObject.*
_ GamBut*.onClick.AddListener(() => ConnectToHost(curhost));//Adds listener of button on ServerName Button i.
//as GamBut is component oon ServerName GameObject i.
They’re located inside of an IEnumerator which is used to refresh the server list. In anycase, I’ve tried many things but for some reason the addlistener no matter which button I press, always connects to the last hostData, dispite attempting to assign one on each button i, for that host i’s host data.
In anycase, hopefully someone here can explain what’s happening. Additionally here is the ConnectToHost function which is being called by the addlistener.
public void ConnectToHost(HostData SelHost){
if (SelHost != null) {
Network.Connect (SelHost);
Debug.Log("connecting to " + SelHost.gameName);
}
}*_
as said, the parameter being sent on all buttons ends up being hostData[hostData.Length - 1] (or the last hostData array cell.) This bug has kept me busy all day, hopefully someone can shed some light on what I’m doing wrong.