Help with button (ArgumentOutOfRangeException: Index is less than 0 or more than or equal to the list count.)
i'm having a problem regarding on saving a name using an EVENT to my button.. i'm sure that i have done it correctly without error but my program is displaying this when i clicked my instantiated button..: (see attached image) really stucked in it haha. btw, the event OnClick.AddListener has no effect in my instatiated button, it does not display userAccounts as its OnClick event Here's my code, hope it'll help. thank you :)
public class ManageAccounts : MonoBehaviour
{
ConnectionDatabase cd;
// Use this for initialization
public GameObject accountContainer;
void Start ()
{
cd = Camera.main.GetComponent <ConnectionDatabase> ();
retrieveAccounts ();
}
private void retrieveAccounts ()
{
string query = "SELECT username FROM accounts;";
IDataReader reader = cd.SelectQuery (query);
while (reader.Read ()) {
GameObject account = Instantiate (accountContainer) as GameObject;
account.transform.SetParent (this.transform, false);
account.transform.GetChild (0).GetComponent <Text> ().text = reader.GetString (0);
account.GetComponent <UnityEngine.UI.Button> ().onClick.AddListener (() => userAccount (reader.GetString (0)));
}
}
public void userAccount (string account)
{
AccountMananger.Instance.accName = account;
SceneManager.LoadScene ("menu");
}
}
Answer by Jomelskie · Mar 12, 2017 at 02:32 AM
Solved.
i've just assign a string variable rather than accessing the reader.GetString(0) and placing it in the parameter of userAccounts
private void retrieveAccounts ()
{
string query = "SELECT username FROM accounts;";
IDataReader reader = cd.SelectQuery (query);
while (reader.Read ()) {
GameObject account = Instantiate (accountContainer) as GameObject;
account.transform.SetParent (this.transform, false);
string acc = reader.GetString (0);
account.transform.GetChild (0).GetComponent <Text> ().text = acc;
account.GetComponent <UnityEngine.UI.Button> ().onClick.AddListener (() => userAccount (acc));
}
}
Your answer
Follow this Question
Related Questions
Does multiple spamming a button break it? 2 Answers
Unity 3D with Arduino Code Question 2 Answers
Problem with Application.Quit 2 Answers
Creating dynamically moving buttons/GUI objects. 1 Answer
A doubt on loading Scenes 0 Answers