UNITY3D淡入淡出效果

测试工程,主要思想是通过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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值