Color of Center Pixel in Sprite

How do you get the color of the center pixel in a sprite?
I have a 64x64 sprite, so I want the pixel at 32, 32.

        Texture2D myTexture = egg.GetComponent<SpriteRenderer>().sprite.texture;

What I tried:

        Color centerSpriteColor = myTexture.GetPixel(myTexture.width/2, myTexture.height/2);

Does anyone know what I’m doing wrong?

1 Like

What happened when you tried that?

I do get a color, but it isn’t the center sprite pixel color.

The full context is that I’m trying to change some particle colors to whatever color is at the center of a sprite that’s flipping through a strip [sprite mode = multiple, pixels per unit is 32].

        print(thisEgg.GetComponent<SpriteRenderer>().sprite.name);
        Texture2D myTexture = thisEgg.GetComponent<SpriteRenderer>().sprite.texture;
        Color centerSpriteColor = myTexture.GetPixel(myTexture.width / 2, myTexture.height / 2);
        centerSpriteColor.a = 1;
        Debug.Log(centerSpriteColor);
        var main = ps.main;
        main.startColor = centerSpriteColor;

There’s a GIF here to demonstrate what color I’m currently getting:
https://i.gyazo.com/87442c22ead57b638491afff604f14c8.mp4

You’re getting the same color every time (and that color looks like a “real” value from somewhere, not a default value like pure black or pure white). That suggests to me you’re probably somehow using the same texture every time.

Are you perhaps using any sort of sprite atlas, where multiple sprites are stored in different parts of a single texture?

Thank you so much! You’re right, and I finally figured it out.

For other people who stumble on this thread, the solution is this:

Rect myRect = thisEgg.GetComponent<SpriteRenderer>().sprite.textureRect;

and then getting myRect.center for the location of the current sprite’s center pixel.