Search Unity

Question Weird interaction with AspectRatioFitter and changing anchors via script

Discussion in 'Editor & General Support' started by Rayeloy, Dec 15, 2023.

  1. Rayeloy


    Feb 12, 2017
    I have the following function called in the editor whenever I click up the mouse 1 button:

    Code (CSharp):
    1.         void AnchorsToCorners()
    2.         {
    4.             RectTransform t = transform.GetComponent<RectTransform>();
    5.             RectTransform pt = transform.parent.GetComponent<RectTransform>();
    7.             if (t == null || pt == null) return;
    9.             Vector2 newAnchorsMin = new Vector2(t.anchorMin.x + t.offsetMin.x / pt.rect.width,
    10.                                                 t.anchorMin.y + t.offsetMin.y / pt.rect.height);
    11.             Vector2 newAnchorsMax = new Vector2(t.anchorMax.x + t.offsetMax.x / pt.rect.width,
    12.                                                 t.anchorMax.y + t.offsetMax.y / pt.rect.height);
    14.             t.anchorMin = newAnchorsMin;
    15.             t.anchorMax = newAnchorsMax;
    16.             t.offsetMin = t.offsetMax = new Vector2(0, 0);
    17.         }
    I expect that when doing a change to the rectTransform, (dimensions or position) it will auto set the anchors to corners. This works really well normally, but when paired with the "AspectRatioFitter", it will cause weird interactions. This is due to the AnchorsToCorners firing the OnRectTransformDimensionsChanged event:

    My question is: how do I make it so that changing the anchors via scripts doesn't fire that event? Is there a works around so that AspectRatioFitter applies the correct dimensions, and then after that the anchors will be set (without calling the AspectRatioFitter again)?

    Here is a small video of the weird interaction:

    Attached Files:

  2. Kurt-Dekker


    Mar 16, 2013
    Doing anything with RectTransform is incredibly fraught and completely tied to the parent as well as the Canvas Scaling mode. I gave up on it utterly.

    It looks like your code is derivative of this code: This is all the crazy code required JUST to put the anchors in the corners of the RectTransform:

    I just make and anchor my parts in the editor, then Instantiate<T>() the ones I want where I want them.

    Fortunately a lot of the UGUI source can be inspected.

    Best of luck to you.
    Rayeloy likes this.