- Home /
How can I use GetPixel to create a color picker?
I have this script which should enable me to get the color of a specific pixel on a gameObject, but it's not working:
if (hit.collider.gameObject.name == "ColorPicker" && Input.GetButtonDown("Fire1")) {
Texture2D tex = (Texture2D)hit.collider.gameObject.renderer.material.mainTexture;
activeColor = tex.GetPixel((int)hit.textureCoord.x, (int)hit.textureCoord.y);
}
I can't figure out why it's not working (by not working, I mean it's consistently returning (.8, .8, .8, 1) as my color), and would appreciate it if somebody could explain to me what I'm doing wrong.
Thanks, Elliot Bonneville
Answer by Mike 3 · Feb 16, 2011 at 01:13 AM
GetPixel takes values from 0 to tex.width and tex.height, whereas textureCoord is normalized (0-1) values, so you're probably just passing 0,0 each time
Either multiply the x by tex.width, y by tex.height, or try using GetPixelBilinear instead:
activeColor = tex.GetPixelBilinear(hit.textureCoord.x, hit.textureCoord.y);
textureCoord is normalized? That's news. Thanks, $$anonymous$$ike!
That did it. I wish I could upvote twice for that helpful piece of info. :)
Upvote for sure! Thank you very much Sir, this worked like a charm!