Alright, let’s not get to 2021.
It’s actually a very simple fix.
The solution is to create your own content size fitter class by extending the existing one, except your custom class has a max width and height.
You need two files: one for the component itself, and another for its editor.
I called mine ContentSizeFitterWithMax
, but pick whichever name you like.
ContentSizeFitterWithMax.cs:
using System;
namespace UnityEngine.UI
{
[AddComponentMenu("Layout/Content Size Fitter With Max", 141)]
[ExecuteAlways]
[RequireComponent(typeof(RectTransform))]
public class ContentSizeFitterWithMax : ContentSizeFitter
{
[NonSerialized]
private RectTransform m_Rect;
private RectTransform rectTransform
{
get
{
if (m_Rect == null)
{
m_Rect = GetComponent<RectTransform>();
}
return m_Rect;
}
}
[SerializeField]
private float m_MaxWidth = -1;
public float maxWidth
{
get => m_MaxWidth;
set => m_MaxWidth = value;
}
[SerializeField]
private float m_MaxHeight = -1;
public float maxHeight
{
get => m_MaxHeight;
set => m_MaxHeight = value;
}
public override void SetLayoutHorizontal()
{
base.SetLayoutHorizontal();
if (maxWidth > 0)
{
if (horizontalFit == FitMode.MinSize)
{
rectTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, Mathf.Min(LayoutUtility.GetMinSize(m_Rect, 0), maxWidth));
}
else if (horizontalFit == FitMode.PreferredSize)
{
rectTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, Mathf.Min(LayoutUtility.GetPreferredSize(m_Rect, 0), maxWidth));
}
}
}
public override void SetLayoutVertical()
{
base.SetLayoutVertical();
if (maxHeight > 0)
{
if (verticalFit == FitMode.MinSize)
{
rectTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, Mathf.Min(LayoutUtility.GetMinSize(m_Rect, 1), maxHeight));
}
else if (verticalFit == FitMode.PreferredSize)
{
rectTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, Mathf.Min(LayoutUtility.GetPreferredSize(m_Rect, 1), maxHeight));
}
}
}
}
}
ContentSizeFitterWithMaxEditor.cs:
using UnityEngine.UI;
namespace UnityEditor.UI
{
[CustomEditor(typeof(ContentSizeFitterWithMax), true)]
[CanEditMultipleObjects]
public class ContentSizeFitterWithMaxEditor : ContentSizeFitterEditor
{
SerializedProperty m_MaxWidth;
SerializedProperty m_MaxHeight;
protected override void OnEnable()
{
base.OnEnable();
m_MaxWidth = serializedObject.FindProperty("m_MaxWidth");
m_MaxHeight = serializedObject.FindProperty("m_MaxHeight");
}
public override void OnInspectorGUI()
{
serializedObject.Update();
EditorGUILayout.PropertyField(m_MaxWidth, true);
EditorGUILayout.PropertyField(m_MaxHeight, true);
serializedObject.ApplyModifiedProperties();
base.OnInspectorGUI();
}
}
}
Proof that it works: I set my max width to 400 on this dialogue choice text, so short choices will expand, but longer choices will wrap, exactly like requested by OP.
2h5q88