Sometimes I like to index my GameObjects (for example, if I have several of them as children of another Gameobject). I created a custom script that has a single variable index:
IndexedGameObject
public class IndexedGameObject : MonoBehaviour
{
public int index;
void Start()
{
index = 0;
}
}
I was trying to create several buttons via code and mark them each with an index when I came across some behavior I didn’t understand.
for (int i = 0; i < 5; i++)
{
GameObject testButton = Resources.Load<GameObject>("Prefabs/testButton");
GameObject instantiatedTestButton = Instantiate(testButton, Vector3.zero, Quaternion.identity);
instantiatedTestButton.transform.SetParent(craftingScrollViewContent.transform, false);
int currentIndex = i;
instantiatedTestButton.GetComponent<Button>().onClick.AddListener(delegate { MyTestButton(instantiatedTestButton, currentIndex); });
instantiatedTestButton.GetComponent<IndexedGameObject>().index = currentIndex;
}
Whenever I click my buttons in game, they run this function:
public void MyTestButton(GameObject button, int index)
{
print(button.GetComponent<IndexedGameObject>().index);
print(index);
}
Interestingly, print(button.GetComponent<IndexedGameObject>().index); always prints 0, and print(index); prints the ith index (correctly).
Why isn’t the index that’s part of my IndexedGameObject updating?