I'm trying to get the % of the color black represents on a Texture2D
public SpriteRenderer paintSprite;
Vector3 paintPos;
public RenderTexture maskProgress;
private float blackAmountTotal;
private float blackAmount;
private Texture2D texture;
void Start()
{
texture= toTexture2D(maskProgress);
for (int x = 0; x < maskProgress.width; x++)
{
for (int y = 0; y < maskProgress.height; y++)
{
blackAmountTotal += texture.GetPixel(x, y).a;
}
}
blackAmount= blackAmountTotal;
}
Texture2D toTexture2D(RenderTexture rTex)
{
Texture2D tex = new Texture2D(rTex.width, rTex.height, TextureFormat.RGB24, false);
RenderTexture.active = rTex;
tex.ReadPixels(new Rect(0, 0, rTex.width, rTex.height), 0, 0);
tex.Apply();
return tex;
}
void Update(){
if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out RaycastHit hit))
{
Vector2 texCoords = hit.textureCoord;
paintPos.x = -1 + (texCoords.x * 2);
paintPos.y = -1 + (texCoords.y * 2);
int pixelXOffset = (int)paintPos.x - (paintSprite.sprite.texture.width / 2);
int pixelYOffset = (int)paintPos.y - (paintSprite.sprite.texture.height / 2);
for (int x = 0; x < paintSprite.sprite.texture.width; x++)
{
for (int y = 0; y < paintSprite.sprite.texture.height; y++)
{
Color pixelDark = paintSprite.sprite.texture.GetPixel(x, y);
Color pixelDarkMask = texture.GetPixel(pixelXOffset + x, pixelYOffset + y);
float removedAmount = pixelDirtMask.a - (pixelDarkMask.a * pixelDark.a);
blackAmount -= removedAmount;
}
}
}
}
private float GetPercentage()
{
return blackAmount/ blackAmountTotal;
}