Search Unity

Unity UI Getting Correct Size on RectTransforms with AspectRatioFitter?

Discussion in 'UGUI & TextMesh Pro' started by greatlakegames, Jun 7, 2022.

  1. greatlakegames

    greatlakegames

    Joined:
    May 7, 2018
    Posts:
    6
    Trying to make a image overlap whatever UI element is selected by an EventSystem.
    There's a follower script that does this:

    Code (CSharp):
    1. void Update() {
    2.     Target = EventSystem.current.currentSelectedGameObject?.GetComponent<RectTransform>();
    3.     if (rectTransform == null || Target == null) return;
    4.     rectTransform.anchorMin = Target.anchorMin;
    5.     rectTransform.anchorMax = Target.anchorMax;
    6.     rectTransform.pivot = Target.pivot;
    7.     rectTransform.sizeDelta = Target.sizeDelta;
    8.     rectTransform.position = Target.position;
    9.  
    10. }
    Everything seems to work fine, EXCEPT on elements using AspectRatioFitter.
    Here's a video and two screenshots:






    As you can see, when I click on the square buttons, the script doesn't get the size of the button correctly. The setup for those square buttons is this:
    - Root w/Grid Layout
    -- Empty Parent RectTransform
    --- Button w/AspectRatioFitter (Fit In Parent, 1:1 ratio)

    Replacing the grid layout with another layout (vertical, horizontal) or even removing the layout completely does not fix the issue, so it must be just regarding the AspectRatioFitter.

    Anyone know what might be causing this and what might be any solutions?
     
    Last edited: Jun 7, 2022
  2. Hosnkobf

    Hosnkobf

    Joined:
    Aug 23, 2016
    Posts:
    1,096
    The anchors are relative to the parent. So, if the
    Target
    has a parent that is not matching the position and size of the
    rectTransform
    , the outcome will be stretched according to the difference of the parents.
     
  3. greatlakegames

    greatlakegames

    Joined:
    May 7, 2018
    Posts:
    6
    Do you know how I could account for the difference between the parent and the Target?
     
  4. Hosnkobf

    Hosnkobf

    Joined:
    Aug 23, 2016
    Posts:
    1,096
    Yes. The easiest way is converting the parents into screen space and then simply do some coordinate transformation.

    I do pretty much that in
    AnchorOverride
    of my asset "Better UI" (see signature). Unfortunately, I'm in holidays and don't have access to the code right now.
     
  5. greatlakegames

    greatlakegames

    Joined:
    May 7, 2018
    Posts:
    6
    I still wasn't able to get this working, does anyone have a solution?