Skip to content

Instantly share code, notes, and snippets.

@ddutchie
Created November 15, 2018 21:07
Show Gist options
  • Save ddutchie/fa396187f24b9c3a1edec645f31d20e5 to your computer and use it in GitHub Desktop.
Save ddutchie/fa396187f24b9c3a1edec645f31d20e5 to your computer and use it in GitHub Desktop.
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()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment