背景和文本自适应长度:
鼠标移入文字自动循环滚动:
1、创建一个image为父物体,在image上加一个mask作为遮罩
2、在image下创建一个text,在text上添加一个ContentSizeFitter组件,设置为水平适应,设置text锚点point x=0
最后在text上增加一个循环滑动脚本:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ScrollText : MonoBehaviour
{
private Text _text;//当前文本
private bool _needScroll;//是否需要滚动
private RectTransform _rect;
[SerializeField]private RectTransform _mask;//文本父物体(文本遮罩)
private void Start() {
SetText("这是一条测试文本循环滚动的文本");
}
/// <summary>
/// 设置文本
/// </summary>
/// <param name="text"></param>
public void SetText(string text)
{
_needScroll = false;
if(_rect == null)
{
_rect = GetComponent<RectTransform>();
}
if(_text == null)
{
_text = GetComponent<Text>();
}
_text.text = text;
transform.localPosition = new Vector3(-_mask.sizeDelta.x / 2, 0, 0);
StartCoroutine("updateSize");
}
IEnumerator updateSize()
{
yield return new WaitForEndOfFrame();
if(_rect.sizeDelta.x <= _mask.sizeDelta.x)
{
//文本比遮罩小,不需要滚动
_needScroll = false;
}
else
{
_needScroll = true;
}
}
private void FixedUpdate()
{
if(_needScroll)
{
if(_rect.localPosition.x > 0 - (_rect.sizeDelta.x + _mask.sizeDelta.x / 2) )
{
_rect.localPosition = new Vector3(_rect.localPosition.x - 1, 0, 0);
}
else
{
transform.localPosition = new Vector3(_mask.sizeDelta.x / 2, 0, 0);
}
}
}
}