关闭

UNITY3D淡入淡出效果

270人阅读 评论(0) 收藏 举报

测试工程,主要思想是通过GUI.DrawTexture()方法将一张跟背景色相同的Texture画到整个画面,实现遮罩效果。然后控制Texture的Alpha值实现淡入淡出效果(Alpha为1时加载下个场景或者干点别的什么)。

自动淡入淡出的时候会出现闪烁,还要考虑下如何修改,如果哪位有好的解决方案欢迎留言交流,不过一般用于场景切换的话稍作修改问题应该不大。

PS:依赖iTween~~~请先下载iTween ^_^

复制代码
 1 using UnityEngine;
 2 using System.Collections;
 3 
 4 public class BlackFadeEffect : MonoBehaviour
 5 {
 6     public enum TransitionState
 7     {
 8         PAUSE,
 9         OUT,
10         IN
11     }
12 
13     private static BlackFadeEffect instance;
14 
15     //当前效果状态
16     public TransitionState currentState;
17     
18     public Color fadeColor;
19     public bool isAutoOut = true;
20     private Texture2D fadeTexture;
21 
22     public static BlackFadeEffect GetInstance()
23     {
24         if (instance == null)
25         {
26             GameObject effect = new GameObject("BlackFadeEffectInstance");
27             instance = effect.AddComponent<BlackFadeEffect>();
28             
29             DontDestroyOnLoad(effect);
30         }
31 
32         return instance;
33     }
34 
35     void Awake()
36     {
37        
38         
39         fadeColor = Color.black;
40         fadeColor.a = 0;
41      //生成默认2D材质
42         fadeTexture = new Texture2D(1, 1);
43         fadeTexture.SetPixels(new Color[1] { Color.white });
44         fadeTexture.Apply();
45 
46     }
47 
48     void OnGUI()
49     {
50         GUI.color = fadeColor;
51         GUI.depth = -1;
52         GUI.DrawTexture(new Rect(0, 0, Screen.width, Screen.height), fadeTexture);
53     }
54 
55     public void DoTransition(TransitionState state)
56     {
57         if (state == currentState)
58             return;
59 
60         currentState = state;
61 
62         switch (state)
63         {
64             case TransitionState.IN:
65                 BeginTransition(1);
66                 fadeColor.a = 1;
67                 break;
68             case TransitionState.OUT:
69                 BeginTransition(0);
70                 fadeColor.a = 0;
71                 break;
72 
73             default:
74                 fadeColor.a = fadeTexture.GetPixel(0, 0).a;
75                 break;
76         }
77     }
78 
79     private void BeginTransition(float alpha)
80     {
81         iTween.Stop(gameObject, "ValueTo");
82         iTween.ValueTo(gameObject, iTween.Hash("from", fadeColor.a, "to", alpha,"onupdate", "OnFadeUpdate", "oncomplete", "TestComplete"));
83     }
84 
85     private void OnFadeUpdate(float alpha)
86     {
87         fadeColor.a = alpha;
88     }
89 
90     private void TestComplete()
91     {
92         if (isAutoOut && currentState == TransitionState.IN)
93         {
94             DoTransition(TransitionState.OUT);
95         }
96     }
97 }
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:20510次
    • 积分:265
    • 等级:
    • 排名:千里之外
    • 原创:0篇
    • 转载:40篇
    • 译文:0篇
    • 评论:0条
    文章分类
    文章存档