LayoutElement aspect ratio fitter

Here is a script allowing you to keep LayoutElement’s aspect

using UnityEngine;
using UnityEngine.UI;


// attach this to LayoutElement, and it will maintain its aspect.
// Don't use too many of these custom UI scripts (especially nested), since each one lags 1 frame behind,
// when the parent is resized. Also might introduce rect-transform instability, but a couple is ok.
//
// Make sure your LayoutGroup (in parent) has Child controls size ticked, else
// we won't be able to adjust our size!
//
// Igor Aherne  wwww.facebook.com/igor.aherne
// May 2018
[RequireComponent(typeof(LayoutElement))]
[ExecuteInEditMode]
public class LayoutElem_AspectRatioFitter : MonoBehaviour {

    enum Fitting {
        none,
        widthControlsHeight,
        heightControlsWidth,
    }

    [SerializeField] Fitting _alignment = Fitting.none;
    [SerializeField] float _aspect = 1.0f;

    [SerializeField] LayoutElement _layoutElem;
    [SerializeField] RectTransform _myRectTransf;



    void Reset() {
        _layoutElem = GetComponent<LayoutElement>();
        _myRectTransf = GetComponent<RectTransform>() as RectTransform;
    }


    [ExecuteInEditMode]
    void Update() {
        if(_alignment == Fitting.widthControlsHeight){
             float wantedHeight = (int)_myRectTransf.rect.width / _aspect;
             if(_layoutElem.minHeight== wantedHeight){ return; }//prevents lots of every-frame Undo-checkpoints when in unity editor
            _layoutElem.minHeight = wantedHeight;
        }
        else {
             float wantedWidth = (int)_myRectTransf.rect.height * _aspect;
            if( _layoutElem.minWidth == wantedWidth){ return; }
            _layoutElem.minWidth = wantedWidth;
        }
    }//end()
}
2 Likes

If you/someone needs a similar solution but with a “Fit To Parent” system instead of “Width Controls Height” or “Height Controls Width”, check out my solution here: