環境
- Unity5.5
- DOTween
コード
test.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;
[RequireComponent(typeof(Camera)),ExecuteInEditMode]
public class FadeEffect : MonoBehaviour {
private Material material;
private bool isFade;
private float _black;
[SerializeField]
private float fadeDuration;
void Awake()
{
material = new Material (Shader.Find ("Custom/Fade"));
}
void Start()
{
StartCoroutine (gameLogic());
}
IEnumerator gameLogic()
{
yield return FadeOut ();
Debug.Log ("Done FadeOut");
yield return FadeIn ();
Debug.Log ("Done FadeIn");
}
public IEnumerator FadeOut()
{
isFade = true;
DOTween.To (black => _black = black, 1.0f, 0.0f, fadeDuration)
.OnComplete (() => {
isFade = false;
});
yield return new WaitWhile (() => isFade == true);
}
public IEnumerator FadeIn()
{
isFade = true;
DOTween.To (black => _black = black, 0.0f, 1.0f, fadeDuration)
.OnComplete (() => {
isFade = false;
});
yield return new WaitWhile (() => isFade == true);
}
void OnRenderImage(RenderTexture source, RenderTexture destination)
{
if (isFade) {
UpdateMaterial ();
Graphics.Blit (source, destination, material);
}
}
void UpdateMaterial()
{
material.SetFloat ("_Black", _black);
}
}
Fade.shader
Shader "Custom/Fade"
{
Properties
{
_MainTex ("Texture", 2D) = "white" {}
_Black ("black", float) = 0.0
}
SubShader
{
// No culling or depth
Cull Off ZWrite Off ZTest Always
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float2 uv : TEXCOORD0;
float4 vertex : SV_POSITION;
};
v2f vert (appdata v)
{
v2f o;
o.vertex = mul(UNITY_MATRIX_MVP, v.vertex);
o.uv = v.uv;
return o;
}
sampler2D _MainTex;
float _Black;
fixed4 frag (v2f i) : SV_Target
{
fixed4 col = tex2D(_MainTex, i.uv);
col = col * _Black;
return col;
}
ENDCG
}
}
}
説明
Scriptからmaterialの_BlackをDOTweenで指定時間で1.0/0.0になるように更新。
fragmentシェーダー側でPropertyの_Blackを全ピクセルに加算。
使い方としてはFadeOutの後に何か処理をしてからFadeIn命令を出す感じです。