Giving Buttons OnClick Items at Runtime

I’m working on a multiplier lobby menu at the moment. It checks how many games are currently being hosted and creates a button for each of them.

I I have a script attached to each button, that holds a simple integer different from all the others.

I need to, when a button is pressed, call a function and pass in the number from the script on the button that was pressed.

For example, I need to in here call the function:

	public void DisplayHostListUI() {
		for(int i = 0; i < hostData.Length; i++) {
			GameObject hostItem = GameObject.Instantiate(hostInfoButton, temp, hostListGUIContainer.transform.rotation) as GameObject;

			hostItem.transform.GetComponent<GameTrackerInfo>().gameListID = i;

			hostItem.transform.FindChild("Game Name").gameObject.GetComponent<Text>().text = hostData*.gameName;*

_ hostItem.transform.FindChild(“Max Players”).gameObject.GetComponent().text = “/” + hostData*.playerLimit.ToString();_
_ hostItem.transform.FindChild(“Connected Players”).gameObject.GetComponent().text = hostData.connectedPlayers.ToString();*_

* //Add OnClick event to call function JoinServer(int serverIndex);*
* }*
* }*
And here simply carry it out:
* public void JoinServer(int serverIndex) {*
* Network.Connect(hostData[serverIndex]);*
* }*
Again, I need to call a function but pass in a variable that was generated at run time as well. I’m lost as how to do it.

You can use AddListener method of UnityEvent. I think something like this should work:

// Get the index number from button
int serverIndex = myButton.GetComponent<ScriptWithNumber>().number;

// Create the delegate
var myUnityAction = new UnityAction(serverIndex => JoinServer(serverIndex));

// Optionally you can remove all listeners
//myButton.RemoveAllListeners;

// Add delegate to onClick event
myButton.onClick.AddListener(myUnityAction);