public Image image;
public string text = "This is a chat that wraps itself";
public float with = 200;
private Text mailText;
RectTransform rect;
RectTransform imgRect;
void Start()
{
mailText = GetComponent<Text>();
rect = GetComponent<RectTransform>();
imgRect = image.GetComponent<RectTransform>();
}
void Update()
{
float curWith = 0;
mailText.text = text;
if (mailText.preferredWidth < with)
curWith = mailText.preferredWidth;
else
curWith = with;
rect.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, curWith);
rect.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, mailText.preferredHeight);
imgRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, curWith);
imgRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, mailText.preferredHeight);
}
RectTransform中有个方法SetSizeWithCurrentAnchors,可以设置这个RectTransform的长度或者宽度。
大于你要的长度时,设置成最大长度,否则设置成当前长度。
imgRect是用来设置聊天背景图片的。
这时会发现有一个问题,当内容不足时,不是向左对齐的 ,而是居中缩放。
这是因为锚点不对,我们停止运行,把文本和背景的锚点都这是到左边居中
再运行就好了。
文章来源地址https://www.toymoban.com/news/detail-743593.html
文章来源:https://www.toymoban.com/news/detail-743593.html
到了这里,关于如何在Unity中实现聊天文本,控制Text文本长度,自动换行的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!