使用方法:
·void RectTransform.SetSizeWithCurrentAnchors(RectTransform.Axis axis, float size)
参数axis:要设置size的轴
参数size:要设置的尺寸值
解释:获取文本框的RectTransform组件后调用该方法设置某轴尺寸
·float Text.preferredHeight
解释:直译为更好的高度,大概意思就是不设限制,根据你的文字行数和字体大小在该轴想占的高度,会占的高度。在宽度固定的情况下显示是三行就是三行的高度。
伪代码示例:
Update()
{
var infoTransform = obj.transform.Find("Info");
infoTransform.GetComponent<Text>().text = $"{msg}";
infoTransform.GetComponent<RectTransform>().SetSizeWithCurrentAnchors(
RectTransform.Axis.Vertical,
infoTransform.GetComponent<Text>().preferredHeight);
}
以上过程中先在父物体下找到Info文本框对象,对其文本赋值,对其y轴也就是高度设置为适应文字高度的值,配合Update()的更新,达成每帧自适应。
后记:
unity自带一个组件ContentSizeFiter可以设置自适应大小。但是工作中使用发现ContentSizeFiter更新RectTransform大小有延迟。比如要弹出一个悬浮窗提示文字,代码中设置开启ContentSizeFiter,然后文字赋值,然后调用显示悬浮窗方法,此时显示的悬浮窗大小是没有自适应效果的