Skip to content

Instantly share code, notes, and snippets.

@AldeRoberge
Created September 9, 2021 03:09
Show Gist options
  • Save AldeRoberge/f0aec39ed5354f7f55e1e431e6f2b28b to your computer and use it in GitHub Desktop.
Save AldeRoberge/f0aec39ed5354f7f55e1e431e6f2b28b to your computer and use it in GitHub Desktop.
Returns the average color of a texture.
/// <summary>
/// Get the average color of a texture. The more samplePoints, the more accurate is the average color but also takes more performance.
/// </summary>
/// <param name="sprite"></param>
/// <param name="_samplePoints"></param>
/// <returns></returns>
public static Color GetTextureAverageColor(Sprite sprite, int _samplePoints)
{
Color sampleColor = new Color();
float r = 0;
float g = 0;
float b = 0;
if (sprite != null)
{
for (int i = 0; i < _samplePoints; i++)
{
Vector2 point = new Vector2(Random.Range(0, sprite.texture.width), Random.Range(0, sprite.texture.height));
sampleColor = sprite.texture.GetPixel((int)point.x, (int)point.y);
r += sampleColor.r;
g += sampleColor.g;
b += sampleColor.b;
}
}
return new Color(r / _samplePoints, g / _samplePoints, b / _samplePoints);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment