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();
}
}