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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice
  4. Dismiss Notice

Programmatically create UI Elements

Discussion in '2D' started by piggybank1974, Dec 6, 2016.

  1. piggybank1974

    piggybank1974

    Joined:
    Dec 15, 2015
    Posts:
    621
    Actually I though this would be easy, err not quite.

    What I'm wanting to do is create a bunch of buttons around a image in a panel, I know I could place them, but If I have more I'll have to change this again so, why not code it, that's what coders do ;)

    I did not want to use a prefab, as I've seen.

    Code (CSharp):
    1.  
    2. GameObject button = new GameObject();
    3.   //button.transform.parent = panel;
    4.   button.AddComponent<CanvasRenderer>();
    5.   button.AddComponent<RectTransform>();
    6.   button.AddComponent<Button>();
    7.  button.AddComponent<Image>();
    8.   button.transform.position = new Vector3(0,0,0);
    9.   //button.GetComponent<RectTransform>().se SetSize(size);
    10.   //button.GetComponent<Button>().onClick.AddListener(method);
    11.  
    I tried the following code above but could not get the image to show up, and yes I know I've not coded that I run the program and select it from the inspector for now I just wanted to know if it was going to work, and err it sort of does but not.

    can anybody shed some light on creating a button programmatically??
     
    mihajlo99nestorovic likes this.
  2. capnjake

    capnjake

    Joined:
    Nov 12, 2013
    Posts:
    53
    Well, are you opposed to creating `GameObjects` instead? You could instantiate a prefab button. But honestly, if you're just trying to render non-dynamic buttons you should just preplace them and then activate when you need them... You are, after all, using an engine that allows simplification of this process.

    If I haven't swayed you then take a look at this article: https://docs.unity3d.com/Manual/HOWTO-UICreateFromScripting.html
     
    mihajlo99nestorovic likes this.
  3. LiterallyJeff

    LiterallyJeff

    Joined:
    Jan 21, 2015
    Posts:
    2,802
    When you create a UI element, you also have to make it a child of a Canvas.
     
  4. piggybank1974

    piggybank1974

    Joined:
    Dec 15, 2015
    Posts:
    621
    Actually if you look from a post a made in the Unity UI here: https://forum.unity3d.com/threads/dynamically-creating-ui-button-element.444848/

    you will see that for some reason, the prefab way just did not work, Image would not work or, Anchor image(top left), could not be changed not sure why.

    I did not want to place these button because one I'm not sure how many I need to be place around an image this may increase later so coding it will make it easier equally, not sure how to do that yet but I'll work it out hopefully

    Anyways I have an update, The poster in there did give me any idea, it looks as if it's the setparent was the issue, once that does the Anchor stuff works, then I tackled the Image problem, so here is the code.

    if you don't set the targetGraphic the button will not look as if it's been pressed.

    Code (CSharp):
    1.  
    2.     void Start ()
    3. {
    4.   GameObject mCanvas = GameObject.Find("Canvas");
    5.  
    6.   GameObject button = new GameObject();
    7.  
    8.   button.AddComponent<CanvasRenderer>();
    9.   button.AddComponent<RectTransform>();
    10.   Button mButton = button.AddComponent<Button>();
    11.   Image mImage =  button.AddComponent<Image>();
    12.   mButton.targetGraphic = mImage;
    13.  
    14.   button.transform.position = new Vector3(0,0,0);
    15.   button.transform.SetParent(mCanvas.transform);  
    16.   button.GetComponent<Button>().onClick.AddListener(Testmethod);
    17.  
    18.     }
    19.    
    20. void Testmethod()
    21. {
    22.   Debug.Log("Button Pressed");
    23. }
    24.  
    I still need to workout the size stuff of the button, now placing might be ok as my canvas is in overlay mode so it's in screen space if I remember correctly.

    Here is an image of what I'm looking for in the end

    idea.png

    I was under the impression that YOU could NOT create this in pure code, I'm not sure if there is any pitfalls as of yet, but, you could code all sorts of things, event the UI for different orientations??
     
  5. unity_yJhvSbiWiR6Vdg

    unity_yJhvSbiWiR6Vdg

    Joined:
    Jun 22, 2018
    Posts:
    4
    how to create a button in script
     
  6. Inxentas

    Inxentas

    Joined:
    Jan 15, 2020
    Posts:
    275
    Code (CSharp):
    1. GameObject icon = new GameObject();
    2. icon.AddComponent<Image>();
    3. icon.transform.SetParent(transform);
    This is what people mean by adding it to a canvas. You just have to tell the transform what it's parent is.
     
    Last edited: Feb 5, 2020
    mihajlo99nestorovic likes this.
  7. a436t4ataf

    a436t4ataf

    Joined:
    May 19, 2013
    Posts:
    1,873
    Because this is still a top hit on Google, and no-one had answered correctly (I knew there was a correct answer, but the name of the API is so badly named that it's imposible to find unless you already know the name):

    Unity provides an API call that creates each UnityUI thing directly from script, with all the required pieces, exactly as if you'd made it in Editor, sparing you from a *lot* of easy-to-make mistakes that lead to difficult-to-tract bugs in your code:
    https://docs.unity3d.com/Packages/com.unity.ugui@1.0/api/UnityEngine.UI.DefaultControls.html