1
\$\begingroup\$

I am creating buttons for each level through script as shown below

private void CreateLevelButtons()
{
    for (int i = 1; i <= no_of_levels; i++)
    {
        Button button = Instantiate(button_prefab);
        button.GetComponentInChildren<Text>().fontSize = 12;
        button.GetComponentInChildren<Text>().text = "Level " + i.ToString();
        button.transform.SetParent(content.transform, false);
        button.onClick.AddListener(() => OnClickLevelButton());
    }
}

In OnClickLevelButton() function I want to determine the level number of the button that was clicked. Is there a way to associate a number to a button so that i can access that number later when the user clicks on the button?

\$\endgroup\$
2
  • \$\begingroup\$ I assume to i variable is similar to the number you want to pass along here, is it not possible to provide this variable on the OnClickLevelButton(i) method? \$\endgroup\$ – sjoerd216 Apr 26 '18 at 9:52
  • \$\begingroup\$ What is holding you from creating a component with an integer field? \$\endgroup\$ – S. Tarık Çetin Apr 26 '18 at 10:22
1
\$\begingroup\$

Yes it is possible, but you have to take care of the closure problem. In order to avoid this, create a temporary variable like this:

private void CreateLevelButtons()
{
    for (int i = 1; i <= no_of_levels; i++)
    {
        int index = i ; // Create variable to avoid closure problem
        Button button = Instantiate(button_prefab);
        button.GetComponentInChildren<Text>().fontSize = 12;
        button.GetComponentInChildren<Text>().text = "Level " + i.ToString();
        button.transform.SetParent(content.transform, false);
        button.onClick.AddListener(() => OnClickLevelButton( index ));
    }
}

void OnClickLevelButton( int i )
{
    Debug.Log("Button #" + i + " has been clicked!");
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.