Hello Forum,
I’m trying to make a menu that is built at runtime.
for (int i = 0; i < bd.ItemCount(); i++) {
buttons.Add((GameObject)Instantiate(button));
buttons*.transform.SetParent(transform, false);*
_ buttons*.transform.GetChild(0).GetComponent().text = bd.GetNameById((byte)i);*_
_ Vector3 position = buttons*.GetComponent().position;
position.y -= 40 * i;
buttons.GetComponent().position = position;*_
_ buttons*.GetComponent().onClick.AddListener(() => {
builder.SelectItem(buttons.transform.GetChild(0).GetComponent().text);
});
}*
You can ignore the first part.
I can imagine why this isn’t working but I have no better idea.
The problem is that the call to the method is when the i does not exist anymore.
How can I know which button called the method?
Thanks!_
Try creating them like this, there’s an issue with the way C# hold references to variables but I can get the buttons to Debug.Log the button number when I create them like this and set the Lambda using temp variables. I believe the issue is fixed in 5 but not used 5 yet so can’t be 100% sure:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class LambdaButtons : MonoBehaviour {
public GameObject prefabButton;
public RectTransform ParentPanel;
// Use this for initialization
void Start () {
for(int i = 0; i < 5; i++)
{
GameObject goButton = (GameObject)Instantiate(prefabButton);
goButton.transform.SetParent(ParentPanel, false);
goButton.transform.localScale = new Vector3(1, 1, 1);
Button tempButton = goButton.GetComponent<Button>();
int tempInt = i;
tempButton.onClick.AddListener(() => ButtonClicked(tempInt));
}
}
void ButtonClicked(int buttonNo)
{
Debug.Log ("Button clicked = " + buttonNo);
}
}
Also sorry it took so long, I saw this at lunch time but was at work for the afternoon. You’ll need a vertical layout group on the panel you put them in so they don’t build on top of each other. I did that and put a layout element on the button prefab with a minimum height of 30, I also stopped the expand on height in the panels vertical group. This is the result I get:
@Icarus619 Like he said in his answer, you’ll need a vertical layout group on the panel you put them in so they don’t build on top of each other.
Here’s a youtube video that will walk you through adding a vertical layout group to your items: ** Unity UI Tutorial - How to make a scrollable list - YouTube **
It also tells you how to implement a scrollbar, in case your list gets taller than the screen.
Good luck.