How to make a flashing white sprite?

Hi everyone,
very simple question.

I want to make my sprite flash in white.

So how am I able to make my sprite white and then access the color via code or animation?

One easy possibility is to place white version of your sprite on top of it. You can control it’s transparency by setting alpha value for sprite renderer’s color from code or animation to make flashing effect.

Better way is to use customised sprite shader.

The post does not solve the original request. I when I wrote this I forgot that I was changing the alpha, not the color, of the sprite. I’m leaving this here for context.

I use the following code to strobe my sprites any color I want (I usually use white as well though). In order for this to work you’ll either need to add a bool name strobing to your class, or remove those part of the code (its just there to stop two or more call to strobe from conflicting with one another).

Basically you call the public function, which first stops if its already strobing, then stores the original color, then calls a helper function. The helper then switches between the two colors, pausing for .3 seconds between.

With this method you don’t need to create a new sprite, just change the color (or alpha) of the existing one.

public void StrobeColor( int _strobeCount, Color _toStrobe )
    {
        if (strobing)
            return;

        strobing = true;

        SpriteRenderer mySprite = this.GetComponent<SpriteRenderer>();
        Color oldColor = mySprite.color;

        StartCoroutine(StrobeColorHelper(0, (( _strobeCount * 2) - 1), mySprite, oldColor, _toStrobe));

    }

    public void StrobeAlpha( int _strobeCount, float a)
    {
        SpriteRenderer mySprite = this.GetComponent<SpriteRenderer>();
        Color toStrobe = new Color(mySprite.color.r, mySprite.color.b, mySprite.color.g, a);
        StrobeColor(_strobeCount, toStrobe);
    }

    private IEnumerator StrobeColorHelper( int _i, int _stopAt, SpriteRenderer _mySprite, Color _color, Color _toStrobe)
    {
        if(_i <= _stopAt)
        {
            if (_i % 2 == 0)
                _mySprite.color = _toStrobe;
            else
                _mySprite.color = _color;

            yield return new WaitForSeconds(.3f);
            StartCoroutine(StrobeColorHelper( (_i+1), _stopAt, _mySprite, _color, _toStrobe));
        }
        else
        {
            strobing = false;
        }
    }

If I create a “New Material” and make the “Rendering Mode” to “Cutout” and the “emission color” white and drag&drop it on my sprite, I’m able to make my sprite.
However it becomes a shader (instead of a material) and I don’t know how to access the shader via code.

@TheDryden
I’m sorry, but could you explain the code a bit please?

Yeah sorry when I posted this I forgot the only color you can’t change the sprite to is white, what I’m actually doing with that code is changing the alpha.

With that said the theory is that you can change the color of any sprite, and it unity will blend the colors in the sprite to try and match the color you chose. This is particularly useful with UI elements as you can have a white element and use the color feature to change it to match the context of the menu.

Unfortunately the default color of sprites is white, which mean you can’t actually use this feature to change the color of a sprite too white. I wrote this code a while ago, and simple forgot that my implementation was to actually change the alpha (to .5 or 50%) instead of changing it to white.

Sorry for the confusion. If you’d like more details on what the code does, ask and I’ll do my best to answer, but for now I’m going to edit my answer to reflect that it doesn’t solve the original question.

@TheDryden
OK, no problem

So in the end is there no other way around but to make another sprite in white?

I mean I can get a white sprite if I play with the shader,
I just do not know how to access the shader’s properties via code.

Haven’t done this by myself, but look from unity’s documentation for Material SetFloat, SetInt etc…

Here’s an example of a modified default Sprite shader with an exposed “_Color” field for color changing.
Colorized Sprite Shader

Shader "Custom/Sprites/Colorized"
{
    Properties
    {
        [PerRendererData] _MainTex ("Sprite Texture", 2D) = "white" {}
        _Color ("Color", Color) = (1,1,1,0)
        [MaterialToggle] PixelSnap ("Pixel snap", Float) = 0
    }

    SubShader
    {
        Tags
        {
            "Queue"="Transparent"
            "IgnoreProjector"="True"
            "RenderType"="Transparent"
            "PreviewType"="Plane"
            "CanUseSpriteAtlas"="True"
        }

        Cull Off
        Lighting Off
        ZWrite Off
        Blend One OneMinusSrcAlpha

        Pass
        {
        CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #pragma multi_compile _ PIXELSNAP_ON
            #include "UnityCG.cginc"
         
            struct appdata_t
            {
                float4 vertex   : POSITION;
                float4 color    : COLOR;
                float2 texcoord : TEXCOORD0;
            };

            struct v2f
            {
                float4 vertex   : SV_POSITION;
                fixed4 color    : COLOR;
                float2 texcoord  : TEXCOORD0;
            };
         
            fixed4 _Color;

            v2f vert(appdata_t IN)
            {
                v2f OUT;
                OUT.vertex = UnityObjectToClipPos(IN.vertex);
                OUT.texcoord = IN.texcoord;
                #ifdef PIXELSNAP_ON
                OUT.vertex = UnityPixelSnap (OUT.vertex);
                #endif

                OUT.color = IN.color;
                return OUT;
            }

            sampler2D _MainTex;
            sampler2D _AlphaTex;
            float _AlphaSplitEnabled;

            fixed4 SampleSpriteTexture (float2 uv)
            {
                fixed4 color = tex2D (_MainTex, uv);

#if UNITY_TEXTURE_ALPHASPLIT_ALLOWED
                if (_AlphaSplitEnabled)
                    color.a = tex2D (_AlphaTex, uv).r;
#endif

                return color;
            }

            fixed4 frag(v2f IN) : SV_Target
            {
                fixed4 textureColor = SampleSpriteTexture (IN.texcoord) * IN.color;
                fixed4 c = lerp(textureColor, _Color, _Color.a);
                c.rgb *= textureColor.a;
                c.a = textureColor.a;
                return c;
            }
        ENDCG
        }
    }
}

Here’s how you can control an object with this material using C#:

using UnityEngine;

[RequireComponent(typeof(SpriteRenderer))]
public class Example : MonoBehaviour
{
    private const string SHADER_COLOR_NAME = "_Color";
    private Material material;

    void Awake()
    {
        // makes a new instance of the material for runtime changes
        material = GetComponent<SpriteRenderer>().material;
    }

    private void Update()
    {
        if (Input.anyKey)
        {
            if (Input.GetKeyDown(KeyCode.Space))
            {
                SetColor(Color.white);
            }

            if (Input.GetKeyDown(KeyCode.Backspace))
            {
                SetColor(new Color(1,1,1,0));
            }
        }
    }

    private void SetColor(Color color)
    {
        material.SetColor(SHADER_COLOR_NAME, color);
    }
}

You should be able to use this to expand into fading alphas, looping for flashing, etc.

7 Likes

In my opinion, the easiest way is to create a new material set to GUI/TextShader, and swap the SpriteRenderers material with it, then swap it back.

I made a quick tutorial about this, you can find the source code in the description:

8 Likes

Hey man,
This looks really neat…I was trying to achieve the same effect with the animator but this makes much more sense…Cheers…=)

Am glad it helped rtncnk. :slight_smile:

Hey this is a post from months ago, but you can do it in the animator by adding the Sprite Renderer’s Material Reference as a property to animate in the Animation window, then changing it for one keyframe or whatever in Record mode.

I found a good shader : GitHub - ilhamhe/UnitySpriteFlash: Example project to show flash effect on Unity sprite. It also can be used to tint the sprite completely.

Is it possible to do this kind of effect with vector graphics?

The above answers work great.
If you want to be able to do it smoothly (or with HDR for glow) I’ve put together a brief video to explain how this is done using URP and Shadergraph.

3 Likes