測試工程,主要思想是通過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 }