- Home /
My onclick action listeners I attach to my buttons as I instantiate them only work once
In my game, I pull a list of games that a player is the admin on from the database. Once I get that list, I instantiate a button for each game that gets pulled from the database, as shown here.
after setting up each of these buttons, I add action listeners to each one, and all I need to send on to their handler is the name that I've attached to the button. What the action handler does is sets the text of the header on the next window to the text of the button that was pressed, this works just fine the first time, but if I go back and click one of the other buttons, the header text stays the same as it was before, and I get a null reference error that looks like this.
here is the offending code:
//Purpose: create a game button for each game the user manages
//Parameters: the list of all games that the user is an admin on
//Returns: nothing
public void addManagerButtons(string gamesList)
{
string[] games = gamesList.Split(';');
for (int i = 0; i < games.Length - 1; i++)
{
GameObject go = (GameObject)Instantiate(gameButtonPrefab);
go.transform.SetParent(managerScrollField.transform);
gameName = games[i].Substring(games[i].IndexOf("GameName") + "GameName".Length);
if (gameName.Contains("|"))
{
gameName = gameName.Remove(gameName.IndexOf("|"));
}
string admin = games[i].Substring(games[i].IndexOf("Admin") + "Admin".Length);
if (admin.Contains("|"))
{
admin = gameName.Remove(admin.IndexOf("|"));
}
if (admin == "true")
{
go.transform.name = gameName;
go.GetComponentInChildren<Text>().text = gameName;
}
//I need to make a view that will show edit rules, view users, etc.
go.GetComponent<Button>().onClick.AddListener(delegate { managingGame(go.GetComponentInChildren<Text>().text); });
}
}
//2. When the button is there, clicking it takes you to a screen that has a few buttons
// a.edit some of a games rules
// b.look at a list of all players that joined and their target, and pins of both
// c.edit a players alive or dead status and their pin
//Purpose: bring up the managing game view for a specific game, or bring it down if its already up
//Parameters: the games name
//Returns: nothing
public void managingGame(string thisGameName)
{
if (!managingGameView.gameObject.active)
{
managingGameView.gameObject.SetActive(true);
StartCoroutine(slideMenu(1f, managingGameView));
}
gameText.GetComponentInChildren<Text>().text = thisGameName;
click.PlayOneShot(click.clip);
}
Answer by deanpackard · Jun 26, 2018 at 01:22 AM
The problem had nothing to do with the prefabs. The problem had something to do with how I was accessing the game text. I dont know why, but when I tried accessing the games text a second time using
gameText.GetComponentInChildren<Text>().text = thisGameName;
Unity wasn't happy with me. I switched my objects reference to the text object itself and access it like this :
gameText.text = thisGameName;
and it works just fine.