Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Have a look at our Games Focus blog post series which will show what Unity is doing for all game developers – now, next year, and in the future.
    Dismiss Notice

[UI] Troubles adding Elements to a Grid Component

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

  1. Vunoo


    Mar 14, 2018
    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


    Dec 5, 2013
    The general strategy should work. I use it all the time for dynamic menus.

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


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


    Apr 19, 2016
    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.