Button.onclick not working

Im trying to setup a load on buttons based on a loop as this will change during gameplay and ive followed how a button is created and it worked just fine.

I think ive changed something in the script but I have no idea what I did to make it angry.

public GameObject button;
    public Item[] ingots = new Item[1];

    public GameObject content;

    Button buttonButton;

    void Start ()
    {
        buttonButton = button.GetComponent<Button>();
    }

    // Update is called once per frame
    public void Activation ()
    {
            for (int i = 0; i < ingots.Length; i++)
            {
                int localButtonNo = i;

                buttonButton.onClick.AddListener(delegate {chosenOre(localButtonNo);});

             
                //Create Button instantiation
                GameObject instantiation = Instantiate(button, new Vector3(0,0,0), Quaternion.identity) as GameObject;

                //Deploy initialisation
                instantiation.transform.SetParent(content.transform, false);
            }
        }
    }

    public void chosenOre(int buttonNo)
    {
        Debug.Log("Hello world " + buttonNo + "!");
        }

Bump

Where do you call Activation?

Its from a button press.

The Activation is definitely being called.

I noticed the click function does get called with the below.

button.GetComponent<Button>().onClick.AddListener(delegate {chosenOre(localButtonNo);});

Although I recently learned GetComponent in a loop is a no no.

So ive established it at the Start.

Is it the instantiated button that you wish to be the ‘owner’ of the onClick event?

Good point, that would make sense and probably is where the error is.

Yup.

GameObject instantiation = Instantiate(button, new Vector3(0,0,0), Quaternion.identity) as GameObject;

                instantiation.GetComponent<Button>().onClick.AddListener(delegate {chosenOre(localButtonNo);});

This works, just need to find a way to shift the GetComponent out of the loop.

Looking into it now.

Why would you want to move GetComponent out of the loop?

I recently had a problem when a similer script was being used as an inventory and every time is open the fps had a dramatic drop. I posted and the GetComponent was the cause as it was being looped a few times for every item.

If you’re trying to add a unique listener for the onClick event to a newly instantiated Button (inside the loop), you’ll have to be calling the GetComponent on that new object to assign…Perhaps your other situation had a similar, but different issue. :slight_smile:

One other option is to have a script on the button itself that you can tie into the onclick event on the button in the inspector. Then when the button is created, it has it’s own script. If you need an index for it, you could have the button just grab it’s sibling index to use.