How can I disable Sprite Renderer in all children of player object?

I have my 2D player animations playing on two separate game objects under the same parent. I’m trying to use the parent script to cause the sprite renderers on the children objects to enable and disable, aka to ‘flash’ when damaged.

I’m new to C# and Unity, so I’m struggling. With the following script, nothing is happening. Can someone please help?

    IEnumerator playerFlash()

    {
        gameObject.GetComponentInChildren<Renderer>().enabled = false;
        yield return new WaitForSeconds(.5f);
        gameObject.GetComponentInChildren<Renderer>().enabled = true;
        yield return new WaitForSeconds(.5f);
        gameObject.GetComponentInChildren<Renderer>().enabled = false;
        yield return new WaitForSeconds(.5f);
        gameObject.GetComponentInChildren<Renderer>().enabled = true;
        yield return new WaitForSeconds(.5f);
        gameObject.GetComponentInChildren<Renderer>().enabled = false;
        yield return new WaitForSeconds(.5f);
        gameObject.GetComponentInChildren<Renderer>().enabled = true;
    }


    public void DamageKnockback(Vector3 knockbackDir, float knockbackDistance, int damageAmount)
    {
        transform.position += knockbackDir * knockbackDistance;

        HeartsHealthVisual.heartsHealthSystemStatic.Damage(damageAmount);
        StartCoroutine(playerFlash());
        Debug.Log("Knocked right the fuck back, bitch.");
    }

Not sure why that wouldn’t work… but it will only do the first Renderer it finds, which might not be the one you expect.

Instead, in your coroutine, do these steps:

  • get a list of all SpriteRenderers below this GameObject (the one the script is on), something like:
SpriteRenderer[] All = GetComponentsInChildren<SpriteRenderer>();
  • now use a for loop to decide how many times you want to flash them on/off:
for (int i = 0; i < 5; i++) {
  • inside that loop make another loop to turn all of the renderers off:
foreach( var sr in All)
{
  sr.enabled = false;
}
  • now yield return new WaitForSeconds however much (0.5f is a bit long, maybe 0.1f?)

  • now redo the for loop that turned the renderers OFF, but turn them ON instead (enable them)

  • yield again an amount of time to show the sprite

  • close the original outer loop of how many flash times (the 5 I put above)

Happily the final result will be the sprites all enabled when the end of the coroutine is reached, i.e., the flash counts have been counted through.

1 Like

Is there any way for the sprites in the parent to be disabled simultaneously rather than in an order?