3

Im finishing up my asset that I'm putting on the asset store. Right now one of the features require the average color of the sprite. Right now I have a public Color to find the average color, where the user can use the color picker or the color wheel or whatever to choose what they think looks like the average color of the sprite. I want to make it so the script automatically calculates the average sprite color, therefore increasing the accuracy by removing human error and increasing the efficiency by not wasting the users time guessing the average sprite color.

1 Answer 1

5

Well there is a post about it in Unity forums. Here the link. And the answer is:

Color32 AverageColorFromTexture(Texture2D tex)
{

        Color32[] texColors = tex.GetPixels32();

        int total = texColors.Length;

        float r = 0;
        float g = 0;
        float b = 0;

        for(int i = 0; i < total; i++)
        {

            r += texColors[i].r;

            g += texColors[i].g;

            b += texColors[i].b;

        }

        return new Color32((byte)(r / total) , (byte)(g / total) , (byte)(b / total) , 0);

}
2
  • Ok, so I tried this: TransitionColor = AverageColorFromTexture(gameObject.GetComponent<SpriteRenderer>().sprite.texture); I get an error message that the texture is not readable. Nov 12, 2015 at 2:42
  • 1
    @user3738071 Mark the texture as readable in its settings on the Inspector in the Editor (you are going to have to switch the texture type to Advanced)
    – Roberto
    Nov 12, 2015 at 4:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.