Dynamic Menu creation

Hello Friends,

I need to create a dynamic menu in which there can be different elements like Buttons/Toggle/Checkboxes/Textboxes. You can say like the one of Google Chrome’s Setting menu. For reference i am attaching a image.

The problem is its is easy to create this type of menu statically. But i need to do this dyynamically so tha

t if i want 10 more buttons/checkboxes so that i can change easily at run time.

Create prefabs for the buttons.

Make a menu builder script that populate the UI.

If you want objects to automatically layout, you need to write some layout class to handle that.

This is not a small question. There are lots of moving parts depending on how complex you want to get it and where you skill level is at. To start somewhere, create a button in Unity and make it a prefab. Then decide which parent they should be instantiated at (the canvas or some panel?).

Maybe something like this:

void AddButton(Button prefab, string name, UnityAction callback)
{
    Button button = Instantiate(prefab);
    button.name = name;
    button.onClick.AddListener(callback);

    Text text = button.GetComponentInChildren<Text>();
    if (text)
        text.text = name;

    RectTransform transform = button.GetComponent<RectTransform>();
    transform.SetParent(canvas.transform);
    transform.anchoredPosition = nextLayoutPosition;
    nextLayoutPosition += Vector3.down * transform.rect.height;
}

Optionally you can access a git repo (or download as zip) here, or view source code files:

Hello Everyone and @Statement .

Sorry for late replying , I solved this dynamic menu creation problem using SetInsetAndSizeFromParentEdge .