循環移動Text (類公告)
阿新 • • 發佈:2019-05-06
src date() ati debug 隨著 component 圖片 pub idt
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; } }
循環移動Text (類公告)