Detect color of clicked pixel

I’ve searched and have found some leads, but there still seems to be a missing link.

This is what I’m doing: In a part of my game, I’m going to have an image of a brain pop up, and I need to be able to detect which part of the brain was clicked. I decided the easiest way to do this would be to make each part of the brain a different color, and then detect the color of the pixel that was clicked. This would then tell me what part of the brain was clicked (I’m open to other solutions!)

My dilemma is this: I can’t seem to figure out how to detect the color of the pixel that was clicked. This is where I am:

//Set 4 colors, each corresponding to a section of the brain image. The image is colored accordingly.
Color blackColor = new Color(0f,0f,0f,1f);
Color whiteColor = new Color(1f,1f,1f,1f);
Color ltGrayColor = new Color(0.5f,0.5f,0.5f,1f);
Color dkGrayColor = new Color(0.25f,0.25f,0.25f,1f);

function OnMouseDown(){ //Click event

//This is where I need help. I need to figure out how to look at the clicked pixel and determine its color, so I can compare it to the 4 colors I specified as variables.

}

This is the closest thing I’ve found, but I don’t really understand how it works: Detect Color in "If" Statement - Questions & Answers - Unity Discussions

I believe I can make my if statement look similar. Do I use this.gameObject? Does that refer to the object I clicked? If so, does something like make sense?

if (this.gameObject.renderer.material.color ==ltGray){
Do stuff
}

Even then, does that get the pixel color, or some color from the entire material (which will not be one solid color)?

Haven’t done anything with GetPixel yet, but here’s a supposedly working script (if IsReadable is enabled on the texture)

Get pixel should probably be ok, but if it was me, If you know what the image is (ie it’s not generated at runtime or by the user) then just make 4 mesh colliders that approximate the clickable areas.

I appreciate the help, but I guess I’m still not sure how to do that in an if statement. I think it’ll be something like:

function OnMouseDown(){

if (blackColor == something.getpixel){

do stuff

}

}

But what is the something? Also, would this be attached to the gameobject that’s textured with the brain image?

The ‘something’ is renderer.material.mainTexture, assuming that this script is attatched to the object with the texture.
You will have to calc the getpixel x and y numbers using a raycast, raycastHit.textureCoords, and multiply up by the textures width and height (all covered in the docs)

  1. need mesh collider
  2. some badly uv-mapped models may return strange uvs
  3. can then simply Unity - Scripting API: Texture2D.GetPixel but obviously multiply uv result by texture size if 0…1 - also need Read/Write Enabled flag on tex enabled.

Thanks guys. This helps a lot. I’m going to try to implement it.