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 + "!");
}
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.
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.