Search Unity

Setting the size of a UI element based off of its parent

Discussion in 'UGUI & TextMesh Pro' started by IK, Jun 6, 2016.

  1. IK

    IK

    Joined:
    Oct 29, 2012
    Posts:
    34
    Greetings, I am having some difficulty getting the hang of creating a UI from a script. I have a sidebar and I'd like to create a square object in the sidebar that has the exact same width as the sidebar. I thought this would be the solution:
    Code (CSharp):
    1.         float widthOfSideBar = sideBar.GetComponent<RectTransform>().rect.width;
    2.         gameObject.GetComponent<RectTransform>().sizeDelta = new Vector2(widthOfSideBar, widthOfSideBar);
    However it ends up being about 80% of the size at runtime. What is my error?
     
  2. IK

    IK

    Joined:
    Oct 29, 2012
    Posts:
    34
    Looks like I needed to set the local scale to (1,1) after I made it a child of the sidebar.