1.背景(Text移动区域) 添加Mask组件 2.添加Text 设置锚点 添加ContenSizeFitter组件:使Text长度随着text内容改变 using System.Collections;using System.Collections.Generic;using UnityEngine;using UnityEngine.UI;us
1.背景(Text移动区域)
添加Mask组件
2.添加Text
设置锚点
添加ContenSizeFitter组件:使Text长度随着text内容改变
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using System; public class TextMove : MonoBehaviour { public Image imgMask; //移动区域组件 public Text txt; //存放公告内容 Dictionary<int, string> StrTxt = new Dictionary<int, string>(); float maskWidth; // 遮罩的宽度 (text起始位置 float txtWidth; // 文本宽度 float speed = 30; // 移动速度 int txtid; private void Start() { maskWidth = imgMask.GetComponent<RectTransform>().rect.width; UnityEngine.Debug.Log("遮罩宽度:" + maskWidth); StrTxt.Add(0, "欢迎来到八点上班个发射"); StrTxt.Add(1, "学习使我进步不熬夜不追剧"); StrTxt.Add(2, "只有10086嘘寒问暖"); } private void Update() { //未移动时给Text赋值 250开始位置 if (txt.transform.localPosition.x >= 250) { showTxt(txtid); } else if (txt.transform.localPosition.x < -(txtWidth + maskWidth)) //移动到左边时复位 { txtid++; txt.transform.localPosition = new Vector3(255, 0, 0); if (txtid > StrTxt.Count-1) { txtid = 0; } } txtWidth = txt.GetComponent<RectTransform>().rect.width; if (txtWidth != 0) { txt.transform.Translate(Vector3.left * Time.deltaTime * speed); } } void showTxt(int id) { //通过key获取value string strvalue = ""; if (StrTxt.TryGetValue(id, out strvalue) == false) throw new System.Exception("gradDic TryGetValue Failure! tmp:" + strvalue); txt.text = strvalue; } }