- Home /
Weird behavior when trying to add an index to a button
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?
Answer by Rechronicle · Oct 12, 2021 at 03:11 AM
probably because the index at 'button.Getcomponent().index' is different than 'print(index)'?
The index parameter won't be going in 'button.Getcomponent().index'
You can see I'm setting the index value of the component in the line right below adding the listener.
instantiatedTestButton.GetComponent<IndexedGameObject>().index = currentIndex;
why isn't that line saving the index of the IndexedGameObject
?