How do I find all spriteRenderers in a scene?

I am trying to find all game objects that have a sprite renderer in my scene. These two methods don’t work:

// this just finds ALL gameobjects in the scene, instead of just sprite renderers
SpriteRenderer[] allSprites = FindObjectsOfType<SpriteRenderer>();

// this only looks in the current gameobject, but not in the whole scene:
SpriteRenderer[] allSprites = GetComponentsInChildren<SpriteRenderer>();

If I use a forEach to loop through all gameObjects and manually check if they have a spriteRenderer it works, but there must be a faster way?

GameObject[] allObjects = FindObjectsOfType<GameObject>();
        foreach (GameObject go in allObjects) {
            SpriteRenderer sprite = go.GetComponent<SpriteRenderer>();
            if(sprite) {
                Debug.Log("this is actually a sprite");
            }
        }

This way should definitely work:

SpriteRenderer[] allSprites = FindObjectsOfType<SpriteRenderer>();

I’m not sure how it’s possible that you would be getting GameObjects that don’t have a SpriteRenderer because this returns an array of SpriteRenderers directly.

2 Likes

Hmmmm it seems I just logged the wrong value… it is indeed working!

1 Like