Flashing Sprite Function won't Work

I’m basically trying to make a function that will make the player’s sprite flash when it’s taken damage and I’ve done this using a IEnumertor:

float flashTimer = 0;
	IEnumerator Flashing()
	{
		SpriteRenderer playerSprite = gameObject.GetComponent<SpriteRenderer>();

		while(takenDamage == true)
		{	
			flashTimer = flashTimer + Time.deltaTime;
			Debug.Log(flashTimer);

			while(flashTimer < 4f)
			{
				playerSprite.sprite = null;
				yield return new WaitForSeconds(0.2f);
				playerSprite.sprite = heartSprite;
			}	

			if(flashTimer >= 4f)
			{
				//playerSprite.sprite = heartSprite;
				takenDamage = false;
				states = playerStates.Normal;
				flashTimer = 0;
			}
		}
	}

I simply tried changing the sprite from null to a already assigned sprite but when i run the function, all that happens is the players sprite disappears and never appears again unless I uncomment the line: “//playerSprite.sprite = heartSprite;”. I’m not sure what I’m doing wrong so I was wondering if someone would be able to help me figure out what is wrong?

Thanks

Well, in your while loop you only have one yield statement. So each iteration you only wait once. So you effectively execute those two lines one after the other:

playerSprite.sprite = heartSprite;
playerSprite.sprite = null;

You need to wait after each state change. Furthermore you will never exit the while loop since flashTimer doesn’t change inside your while loop. It will always stay at some value below 4. You have to increase it inside the while loop. Time.deltaTime doesn’t make sense here since the increment line isn’t executed every frame. Since we wait two times 0.2 seconds (== 0.4) we just have to increment flashTimer by that value.

         while(flashTimer < 4f)
         {
             playerSprite.sprite = null;
             yield return new WaitForSeconds(0.2f);
             playerSprite.sprite = heartSprite;
             yield return new WaitForSeconds(0.2f);
             flashTimer = flashTimer + 0.4f;
         }