Is there a better way to flash my character when hit?

My intended behavior is that when my character is hit, the sprite will decrease in alpha by 0.5f then go back to normal a few times creating a flashing effect.

After several iterations I finally got the result I wanted, but I can’t help but feel this is extremely inefficient and there must be a better way of doing it

I know I have some spaghetti code going on, this is one of my first projects so I’m not too worried about that just getting a hang of things.

The below functions are in the playermovement script

public void YouAreHit()
    {
        StartCoroutine(IGotHit());

    }    

public IEnumerator IGotHit()
    {
        while(isHit < 15)
        {
            while (isFlashing == false)
            {
                yield return new WaitForSecondsRealtime(0.05f);
                _renderer.color = new Color(1f, 1f, 1f, 0.5f);
                isHit++;
                isFlashing = true;
                if (isFlashing == true)
                {
                    break;
                }
            }
            while (isFlashing == true)
            {
                yield return new WaitForSecondsRealtime(0.05f);
                _renderer.color = new Color(1f, 1f, 1f, 1.0f);
                isHit++;
                isFlashing = false;
                if (isFlashing == false)
                {
                    break;
                }
            }
        }
    }

This is the enemy script for when it hits the player

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.tag == "Player")
        {
            FindObjectOfType<Health>().lives -= 1;
            FindObjectOfType<PlayerMovement>().isHit = 0;
            FindObjectOfType<PlayerMovement>().YouAreHit();
        }
    }

Overall, your approach is fine, but if you really want to squeeze efficiency, you could use a Shader/Shader Graph to do the animation to utilize the GPU aspect of it.

The Shader can do the blinking, color, and blink frequency.

The blink itself could be passing in a color into the emission/mult with texture in the Diffuse/Albedo, multiplied by a Sine node with a multiplied Time node for blink frequency.