Skip to content

Instantly share code, notes, and snippets.

@snarlynarwhal
Last active September 11, 2020 23:10
Show Gist options
  • Save snarlynarwhal/7e29452e196be51b7f9700b2b3a25f40 to your computer and use it in GitHub Desktop.
Save snarlynarwhal/7e29452e196be51b7f9700b2b3a25f40 to your computer and use it in GitHub Desktop.
Makes the sprite alpha flicker.
using UnityEngine;
public class SpriteAlphaFlicker : MonoBehaviour
{
public float flickersPerSecond = 15f;
public float flickerRangeMin = -0.1f;
public float flickerRangeMax = 0.1f;
private SpriteRenderer spriteRenderer;
private float alpha;
private float time;
private void Start()
{
spriteRenderer = GetComponent<SpriteRenderer>();
alpha = spriteRenderer.color.a;
}
private void Update()
{
if (GetMillisecs() > 1000f / flickersPerSecond)
{
float newAlpha = alpha + Random.Range(flickerRangeMin, flickerRangeMax);
Color newColor = spriteRenderer.color;
newColor.a = newAlpha;
spriteRenderer.color = newColor;
ResetTime();
}
}
private float GetMillisecs()
{
return (Time.realtimeSinceStartup - time) * 1000;
}
public void ResetTime()
{
time = Time.realtimeSinceStartup;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment