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

    Rayeloy

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


    Code (CSharp):
    1.         void AnchorsToCorners()
    2.         {
    3.  
    4.             RectTransform t = transform.GetComponent<RectTransform>();
    5.             RectTransform pt = transform.parent.GetComponent<RectTransform>();
    6.  
    7.             if (t == null || pt == null) return;
    8.  
    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);
    13.  
    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:

    https://docs.unity3d.com/2017.3/Doc...ehaviour.OnRectTransformDimensionsChange.html

    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

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,726
    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:

    http://forum.unity3d.com/threads/sc...hor-to-gui-object-size-rect-transform.269690/

    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.

    https://github.com/Unity-Technologies/uGUI

    Best of luck to you.
     
    Rayeloy likes this.