一、首先,我們先創建一個Text
依次選擇Component→UI→Text創建一個Text,創建完成后如下:
二、創建完成后,在Project面板點擊Create→C# Script,本例命名為InAndFade
三、編寫代碼之前,為了確保能夠調用到Text類,所以要先手動引入命名空間
using UnityEngine.UI;
四、完整代碼如下
1 public class InAndFade : MonoBehaviour 2 { 3 //漸隱漸現 4 public bool Show = true; 5 public bool Fade = false; 6 public float duration = 2.5f; 7 public float timeFromStart = 0f; //從場景加載開始經過這些時間后再發生 8 //向下滑動 9 public bool isSlide = true; //是否從上往下滑動 10 public float offset = -1.0f; //偏差為10 11 //變色 12 public bool isChangeColor = true; 13 //等待 14 private bool wait = true; 15 void Start() 16 { 17 if (Show && Fade) 18 { 19 Fade = false; 20 } 21 else if (!Show && !Fade) 22 { 23 Show = true; 24 } 25 } 26 IEnumerator Wait() 27 { 28 yield return new WaitForSeconds(timeFromStart); 29 } 30 void Update() 31 { 32 #region 變色代碼 33 if (isChangeColor) 34 { 35 Color nowColor = gameObject.GetComponent<Text>().color; 36 if (nowColor.r != 0 && nowColor.g != 255 && nowColor.b != 255) 37 { 38 nowColor.r--; 39 nowColor.g += 2.8f; 40 nowColor.b += 0.9f; 41 } 42 gameObject.GetComponent<Text>().color = nowColor; 43 if (nowColor.g >= 40 && nowColor.g <= 255) 44 { 45 nowColor.g--; 46 } 47 } 48 #endregion 49 #region 滑動代碼 50 if (isSlide) 51 { 52 Vector3 initialPos = gameObject.GetComponent<Transform>().position; 53 float posProportion = Time.time / duration; 54 Vector3 nowPos = new Vector3(initialPos.x, Mathf.Lerp(initialPos.y + offset, initialPos.y, posProportion), initialPos.z); 55 gameObject.transform.position = nowPos; 56 } 57 #endregion 58 #region 漸隱漸現代碼 59 if (wait) 60 { 61 StartCoroutine(Wait()); 62 } 63 if (Fade) 64 { 65 if (Time.time > duration) 66 { 67 Destroy(gameObject); 68 } 69 Color newColor = gameObject.GetComponent<Text>().color; 70 float proportion = Time.time / duration; 71 newColor.a = Mathf.Lerp(1, 0, proportion); 72 gameObject.GetComponent<Text>().color = newColor; 73 } 74 if (Show) 75 { 76 Color newColor = gameObject.GetComponent<Text>().color; 77 float proportion = Time.time / duration; 78 newColor.a = Mathf.Lerp(0, 1, proportion); 79 gameObject.GetComponent<Text>().color = newColor; 80 } 81 #endregion 82 } 83 }