Search Unity

  1. Unity 2019.2 is now released.
    Dismiss Notice

[UI] Troubles adding Elements to a Grid Component

Discussion in 'Getting Started' started by Vunoo, Oct 25, 2018.

  1. Vunoo

    Vunoo

    Joined:
    Mar 14, 2018
    Posts:
    6
    Hello guys, I've been trining to add Button (with a Layout Element component) to a Vertical Layout Group (with a Content Size filter with spacing between elements added). If I manually drag them into the Grid they appear with the correct format, spacing and text layout. But if I add them as a prefab from script they get added into the grid with wrong sizes, no spacing and wrong text format. Am I doing it wrong from the code part? This is what I have:

    Code (CSharp):
    1.     public void fillLayoutData()
    2.     {
    3.         for (int i = 0; i < module_descs.Count; i++)
    4.         {
    5.             Button btn = Instantiate(detailsButton);
    6.             btn.GetComponentInChildren<Text>().text = module_descs[i];
    7.             btn.transform.SetParent(layout_group.transform);
    8.             //.transform.parent = details_panel.transform;
    9.         }
    10.     }
    Where "module_descs" is a List of strings to add as label for the buttons (I would LOVE if I could use TMpro_Text instead as the default text is very bad), "detailsButton" is the button prefab with the componnents specified above and "layout_group" is the grid GameObject where I want to add these elements.

    Do you know why the buttons are not fitting in with the format I want? Thank you so much for taking the time to read this and help me out, I trully appreciate it!
     
  2. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,514
    The general strategy should work. I use it all the time for dynamic menus.

    Have you applied the changes to your prefab?
     
  3. Vunoo

    Vunoo

    Joined:
    Mar 14, 2018
    Posts:
    6
    You mean saving the prefab with the necessary components? Yes, I did. Unfortunately, its not working as intended.
     
  4. Bill_Martini

    Bill_Martini

    Joined:
    Apr 19, 2016
    Posts:
    378
    Kind of think you have something setup wrong, that should work. Maybe try to make another button leave it in scene but off camera view and use that as your prefab.

    I don't see why you can't remove the text component from the button and replace it with text from TMPro. if your text is not displayed nice, maybe you screen resolution is weird, just a guess on that though.