using UnityEngine;
[ExecuteInEditMode, RequireComponent
(typeof(UIPanel
))] public class UIConstrain : MonoBehaviour
{
private UIPanel Panel { get { return _panel ?? (_panel = GetComponent<UIPanel>()); } }
private UIPanel _panel;
private UIRoot Root { get { return _root ?? (_root = GetComponentInParent<UIRoot>()); } }
private UIRoot _root;
private static float Ratio { get { return Screen.width*1f/Screen.height; } }
private float MaxRatio { get { return Root.manualWidth*1f/Root.manualHeight; } }
private void Start() { UpdateAnchors(); }
#if UNITY_EDITOR
private void Update() { if (!Application.isPlaying) { UpdateAnchors(); } }
#endif
private void UpdateAnchors()
{
if (!Root || !Panel) { return; }
// Ratio is less than max ratio, so release panel constraints.
if (Ratio < MaxRatio && Panel.clipping == UIDrawCall.Clipping.ConstrainButDontClip) { Panel.clipping = UIDrawCall.Clipping.None; }
// Ratio is more than max ratio, so constrain panel.
else if (Ratio > MaxRatio && Panel.clipping == UIDrawCall.Clipping.None)
{
Panel.clipping = UIDrawCall.Clipping.ConstrainButDontClip;
Panel
.baseClipRegion = new Vector4
(Panel
.baseClipRegion.x, Panel
.baseClipRegion.y, Root
.manualWidth, Root
.manualHeight); }
}
}