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

Problems determining RectTransform's height

Discussion in 'UGUI & TextMesh Pro' started by Amegatron, May 16, 2015.

  1. Amegatron

    Amegatron

    Joined:
    May 16, 2015
    Posts:
    2
    Hello everybody!

    I've got a problem determining the height of a needed RectTransform at runtime.

    I have a quite complicated UI driven by numerous LayoutElements and Layout Vertical (and Horizontal) groups. The problem is that GetComponent<RectTransform>().rect on a nested element inside this UI returns quite strange rects: some only have non-zero width (while zero height), some have only zero values (x, y, width and height). I suppose this is because outer Layout Group, which drives this element, somehow disturbes the rect.

    So the question is: how to determine actual size of a RectTransform, which is driven by LayoutElement or Layout Group?

    Thanks.

    P.S. Also there is a Content Size Fitter attached to the top panel which holds other UI elements.
     
    Last edited: May 16, 2015
  2. Josh-Armour

    Josh-Armour

    Joined:
    Aug 8, 2014
    Posts:
    6
    I have the same issue, cant seem to find a solution if anyone can help. The same prefab works in its own scene, but when put in a complex one elements say they are 0 height/ 0 width when they are not
     
  3. Amegatron

    Amegatron

    Joined:
    May 16, 2015
    Posts:
    2
    Meanwhile I got a workaround for this for static elements, which do not change their size during runtime.
    I'll give an example of height.
    First, I wrote down the height of the needed element in the inspector in the scene, let it be 48.
    Then, when initializing the scene I get the vertical "scale factor" of main canvas:
    Code (CSharp):
    1. var canvas = GameObject.Find ("Canvas");
    2. _scaleFactorY = canvas.GetComponent<RectTransform> ().localScale.y;
    3.  
    Later actual height of the element could be calculated by multiplying those two values:
    Code (CSharp):
    1. 48 * _scaleFactorY
    For width everything is the same except you should take localScale.x of Canvas' RectTransform.

    Hope this will help you :)
     
  4. nmd

    nmd

    Joined:
    Aug 5, 2014
    Posts:
    3
    Hi, it's because the auto layout is not calculated until the end of the frame (presumably on LateUpdate ?). Take a look at the bottom of this page:
    http://docs.unity3d.com/Manual/UIAutoLayout.html

    Use the OnRectTransformDimensionsChange method and you'll get the correct rect.width and rect.height values.