andyz
February 5, 2024, 11:50am
18
Neohun:
Alright, let’s put an end to this madness here. Since this is the top thread on google I’m gonna post the code here once and for all for those who struggle with this nonsense. This script basically extends the content size fitter to clamp the sizeDelta of the rectTransform. So instead of “ContentSizeFitter” you’ll use this component. Just create a new script and copy paste the following code:
using UnityEngine;
using UnityEngine.UI;
using UnityEditor;
public class ContentSizeFitterEx : ContentSizeFitter {
// Define the min and max size
public Vector2 sizeMin = new Vector2(0f, 0f);
public Vector2 sizeMax = new Vector2(1920f, 1080f);
public override void SetLayoutHorizontal() { // Override for width
base.SetLayoutHorizontal();
// get the rectTransform
var rectTransform = transform as RectTransform;
var sizeDelta = rectTransform.sizeDelta; // get the size delta
// Clamp the x value based on the min and max size
sizeDelta.x = Mathf.Clamp(sizeDelta.x, sizeMin.x, sizeMax.x);
// set the size with current anchors to avoid possible problems.
rectTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, sizeDelta.x);
}
public override void SetLayoutVertical() { // Override for height
base.SetLayoutVertical();
// get the rectTransform
var rectTransform = transform as RectTransform;
var sizeDelta = rectTransform.sizeDelta; // get the size delta
// Clamp the y value based on the min and max size
sizeDelta.y = Mathf.Clamp(sizeDelta.y, sizeMin.y, sizeMax.y);
// set the size with current anchors to avoid possible problems.
rectTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, sizeDelta.y);
}
}
[CustomEditor(typeof(ContentSizeFitterEx))]
public class ContentSizeFitterExEditor : Editor {
// override the editor to be able to show the public variables on the inspector.
public override void OnInspectorGUI() {
base.OnInspectorGUI();
}
}
Edit: The code is updated for a better version that works without messing with anchors to avoid possible problems with different type of anchors.
Thank you random Unity saver, lovely simple 1 component solution - why on earth does the Unity size fitter not have max sizes particularly to wrap text?!
5 Likes