Change color of a pixel to either black or white depending on how grey the pixel is
Hello!
I am making a script that "scans" a black and white picture. When i use a black and white picture (32x32 pixels) i always get a few pixels that are grey. I am trying to make these either white or black depending where on the greyscale they are. This is what i have so far:
using UnityEngine;
using System.Collections;
public class CreateBlocks : MonoBehaviour {
public Texture2D heightmap;
private Color color;
public int w;
public Color[] pixels;
void Start () {
pixels = heightmap.GetPixels (0, 0, heightmap.width, heightmap.height);
for (int x = 0; x < heightmap.width; x++){
for (int y = 0; y < heightmap.height; y++){
color = pixels[(y * heightmap.height)+x];
GameObject obj = GameObject.CreatePrimitive(PrimitiveType.Cube);
obj.transform.position = new Vector3 (x, y, 0);
obj.renderer.material.color = color;
if (color.a > 127.5f)
{
color = Color.black;
}
else
{
color = Color.white;
}
}
}
}
}
But nothing really happens with the grey pixels. According to the RGBA-pallette the a-value is between 0 and 255. 255 is white and 0 is black so all the pixels that are under 127.5 should become black with my if statement, i dont see why its not working.
Thank you
//Taegos
I don't mess with this stuff so I'm just typing what comes to $$anonymous$$d - is ".a" or Alpha the same as "the Color"?
a is one color component. The sprite has 4 componetns: rgba, i want to access a because it works in grayscale since im working in black and white.
Answer by nesis · Aug 25, 2015 at 12:34 AM
Color is a struct. Structs are copy-by-value (like int, float, bool, and string) rather than copy-by-reference (like classes and collections).
This means that you are copying color's value to material.color, and are then changing color's value to black or white (which doesn't affect material.color).
Set color's value first, then copy it to material.color. This will make your script work.
Thank you! Can you show me with an example? I have tried to do as you say but i cant really get it to work.
Wait i got it now, thank you!
ins$$anonymous$$d of using color in the if statement i used obj.renderer.material.color = Color.black;
like this for example:
if (0 < color.b && color.b < Color.gray.b)
{
w = w + 1;
obj.renderer.material.color = Color.black;
}