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

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.