using UnityEngine; using System.Collections; using System.Collections.Generic; public class RollTxt : MonoBehaviour { //支持中文 private string txt = "1234567werweerty74874651rtyrghdfgdgdfg891234wrew56789"; public string showTxt; public int showLength = 8; public int txtLength; public float rollSpeed = 0.1f; private int indexMax; // Use this for initialization void Start () { txtLength = txt.Length; showTxt = txt.Substring(0,showLength); indexMax = txtLength - showLength + 1; } // Update is called once per frame void Update () { GetShowTxt(); } void OnGUI() { GUI.Box(new Rect(200,200,150,20),showTxt); } void GetShowTxt() { if(showLength>=txtLength) { showTxt = txt; } else if(showLength<txtLength) { int startIndex = 0; startIndex = (int)(Mathf.PingPong(Time.time * rollSpeed, 1) * indexMax); showTxt = txt.Substring(startIndex,showLength); } } }
由於有的時候在GUI內輸入一些文字標題的時候,標題的字符長度會超過我們排版要求的長度。有兩種方法解決,第一種就是在超過的部分最后用“…”來代替,第二種就是讓標題滾動起來。
第一種不做討論,第二種還有一種方法,就是給GUI打組,然后動態修改組內標題GUI的X或Y的坐標,但是比較麻煩一些。
由於Mathf.PingPong(float t,float length);這個函數的來回動盪速度是和字符串的長度有關,所以要根據情況調整速度。
注意:Mathf.PingPong(float t,float length);unity官方給出的這個函數並不是我們想的那么好用,當length過大的時候會出現不受控制的情況,不知道為什么。解決方法就是把length全部寫成1,在10以內還是沒什么問題的,然后再后面乘以自己想要控制的數值。