在Unity5中使用C#脚本实现UI的下滑、变色、渐隐渐现效果

时间:2022-05-22 03:55:23

 一、首先,我们先创建一个Text
    依次选择Component→UI→Text创建一个Text,创建完成后如下:

在Unity5中使用C#脚本实现UI的下滑、变色、渐隐渐现效果

二、创建完成后,在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 }