# get pixel from a texture

How would i can get color from a texture using get.pixel function and apply to a cube

``````     var window1 : Rect = Rect(10,20,300,300);
var color1 : Texture2D;
var activeColor : Color;
var size = Vector3 (100, 10, 100);

function OnGUI()
{
window1 = GUI.Window(0,window1,domy,"picker");
}

function domy()
{
GUI.Label(Rect(30,30,145,150),color1);
}

function Update()
{
var mouse1 = Input.mousePosition.x;
var mouse2 = Input.mousePosition.y;
mouse2 = Screen.height - mouse2+20;
var rect = Rect(30,30,200,150);
if (rect.Contains(Vector3(mouse1,mouse2,Input.mousePosition.z)))
{
var x : int = transform.position.x/size.x *color1.width;
var z : int = transform.position.z/size.z *color1.height;
var y : int;
activeColor = color1.GetPixelBilinear(x,y);
Debug.Log(activeColor);
}

``````

}

inside the rect contains i want to use get.pixel to get the color from the texture named color1 when mouse is over the texture and to apply the got color from texture color1 to a cube how is it possible inside this code. i want to create a color picker

First you must convert from the X,Y coordinates of the click to the texture coordinates (typically referred to as U and V.) Then you can fetch the pixel color at that spot.

I don't see a problem with your code to actually get the pixel (using GetPixelBilinear) so that just leaves the texture coordinates.

Texture coordinates always start at 0,0 and go to 1,1. In your picker you are displaying the entire texture in the rectangle (30,30,200,150) so just a little math will convert the coordinates to the 0..1 range.

The following code is not tested, and you may need to flip the Y coordinate, but you'd do something like:

``````var u = (mouse1 - 30) / 200;  // x --> u
var v = (mouse2 - 30) / 150;  // y --> v
// v = 1.0 - v;  //Uncomment this to flip vertically, if necessary
activeColor = color1.GetPixelBilinear(u, v);

``````

(Note: if this was a texture on a 3D object with a collider, you'd instead do a Raycast to figure out where the user clicked, then just read the UV coordinates directly from the RaycastHit record.)