Skip to content

Instantly share code, notes, and snippets.

@cjacobwade
Created July 25, 2018 03:44
Show Gist options
  • Save cjacobwade/3d5544d59635b007b7a53ee60f42bd57 to your computer and use it in GitHub Desktop.
Save cjacobwade/3d5544d59635b007b7a53ee60f42bd57 to your computer and use it in GitHub Desktop.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.ImageEffects;
[ExecuteInEditMode]
public class IndoorMaskEffect : ImageEffectBase
{
[SerializeField]
float _showMaskTime = 0.3f;
public LensManager<bool> showMaskLens = new LensManager<bool>((b) => LensUtils.AllTrue(b, false));
Coroutine _showMaskRoutine = null;
void OnEnable()
{
material.SetColor("_Color", material.GetColor("_Color").SetA(0f));
showMaskLens.evaluateCallback += OnEvaluateShowMask;
}
void OnPostRender()
{
if(showMaskLens || _showMaskRoutine != null)
Graphics.Blit(null as RenderTexture, material);
}
void OnEvaluateShowMask(bool show)
{ _OnEvaluateShowMask(show, false); }
void OnEvaluateShowMask(bool show, bool instant = false)
{ _OnEvaluateShowMask(show, instant); }
void _OnEvaluateShowMask(bool show, bool instant)
{
if (show)
Show(instant);
else
Hide(instant);
}
void Show(bool instant)
{
if (_showMaskRoutine != null)
StopCoroutine(_showMaskRoutine);
_showMaskRoutine = StartCoroutine(ShowMaskRoutine(true, instant));
}
Coroutine Hide(bool instant)
{
if (_showMaskRoutine != null)
StopCoroutine(_showMaskRoutine);
_showMaskRoutine = StartCoroutine(ShowMaskRoutine(false, instant));
return _showMaskRoutine;
}
IEnumerator ShowMaskRoutine(bool showMask, bool instant)
{
Color startColor = material.GetColor("_Color");
Color endColor = startColor.SetA(showMask ? 1f : 0f);
float timer = instant ? _showMaskTime : 0f;
while(timer <= _showMaskTime)
{
timer += Time.deltaTime;
float alpha = timer / _showMaskTime;
material.SetColor("_Color", Color.Lerp(startColor, endColor, alpha));
yield return null;
}
_showMaskRoutine = null;
}
protected override void OnDisable()
{
base.OnDisable();
showMaskLens.evaluateCallback -= OnEvaluateShowMask;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment