- Home /
List of type Button has size set to zero at runtime
I am building a board game using the unity UI system and have a runtime error I have not been able to fix. I have a script called UIController that has a list of all buttons in the scene, I added the button objects into the list variable for the script via the inspector window. At runtime I want to iterate through this list and generate a dictionary with where the key is the button, and the value is a string, this will be used later to modify the text component of the button. I encounter several errors and strange a behaviour at runtime. Below is the code:
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class UIController : MonoBehaviour
{
public List<Button> buttons;
public Dictionary<Button,string> grid;
public void BoardSetup(List<Button> buttonElments)
{
for(int i =0; i < 25; i++)
{
Debug.Log("Button name is " + buttonElments[i].name);
// add a new button + string to the dict
grid.Add(buttonElments[i], "");
// check if the button is a corner space
if (buttonElments[i].name == "GridSpace" || buttonElments[i].name == "GridSpace4" ||
buttonElments[i].name == "GridSpace20" ||
buttonElments[i].name == "GridSpace24")
{
//update the value in the dict
grid[buttonElments[i]] = "T";
//set the actual text in game to the correct char
buttonElments[i].GetComponentInChildren<Text>().text = "T";
}
}
}
void Awake()
{
Debug.Log("list is size is " + buttons.Count);
BoardSetup(buttons);
}
}
Here is a screenshot of my editor window with the errors:
Some notes on the errors and debug logs, before the function is called, the size of the list is 25 (what it should be), the function is able to access the first element of the list and perform the task, but after that I get the index out of bounds error. Then it appears as if the debug statement is called 25 more times and it assumes the list size is zero. Furthermore the index out of bounds is printed out in the console 25 times. The line numbers for the errors are CS 13, and 30. At 13 is the first time in the BoardSetup function that the list is accessed by index, and line 30 is where BoardSetup is called. Any help would be appreciated in figuring out why it seems like the list size changes at runtime, despite no code changing it, and why the index out bounds error is occuring.