# Change the min width/height of a LayoutElement to scale with the screen size

I want to change the Min Width and Min Height configured in my LayoutElement so that they scale proportionate to the screen size.

For example, at a screen resolution of 1920x1080, the min width is 300. Then if I reduce my screen size to 1280x720 (one-third smaller), then the min width should become 200.

How can I do this?

• Is there a specific reason why you are using a LayoutElement in this case? (And if so, what is that reason? and what is the actual effect you are after?) As there might be other (or even better) ways to achieve this, For instance: Don't use LayoutElement, have a direct child of a canvas, setting anchorMin.x to 0 and anchorMax.x to 0.15625 and then setting both 'left' and 'right' to 0 in the inspector would make the width scale with screen size. Oct 2 '20 at 12:42

Presumably you tried writing a script that sets the minWidth property on the LayoutElement attached to the same object, something like this?

using UnityEngine;
using UnityEngine.UI;

[RequireComponent(typeof(LayoutElement))]
public class LayoutElementAdjuster : MonoBehaviour
{
[Tooltip("What fraction of the screen width/height should be used as the minimum?"
+"\n-1 = Don't scale with screen size.")]
public Vector2 minSizeRatio = new Vector2(-1, -1);

[SerializeField, HideInInspector]
LayoutElement _layout;
Vector2 _cachedScreenSize;

private void OnValidate() {
_layout = GetComponent<LayoutElement>();
}

void Update()
{
Vector2 screenSize = new Vector2(Screen.width, Screen.height);

// Avoid dirtying the layout if the screen size has not changed.
if (_cachedScreenSize == screenSize)
return;

// Change the min size only if the layout element is controlling that axis
// and our inspector configuration says we should scale it (ie. non-negative).
if(_layout.minWidth >= 0f && minSizeRatio.x >= 0f)
_layout.minWidth = minSizeRatio.x * screenSize.x;

if(_layout.minHeight >= 0f && minSizeRatio.y >= 0f)
_layout.minHeight = minSizeRatio.y * screenSize.y;

// Save our current screen size, so we can react only when it changes.
_cachedScreenSize = screenSize;
}
}