GetPixel() returns only one value

Hi,

i’m trying to get color codes out of an texture which has a few different colored areas.
Here’s my code:

public class ColorRef : MonoBehaviour {

Color pixelColor;

public Camera cam;

void Start() {

        cam = GetComponent<Camera>();
	}
	void Update() {
		if (!Input.GetMouseButton(0))
			return;
		
		RaycastHit hit;
		if (!Physics.Raycast(cam.ScreenPointToRay(Input.mousePosition), out hit))
			return;
		
		Renderer rend = hit.transform.GetComponent<Renderer>();
		MeshCollider meshCollider = hit.collider as MeshCollider;
		if (rend == null || rend.sharedMaterial == null || rend.sharedMaterial.mainTexture == null || meshCollider == null)
			return;

		Texture2D tex = rend.material.mainTexture as Texture2D;
		Vector2 pixelUV = hit.textureCoord;

		pixelColor = tex.GetPixel ((int)hit.textureCoord.x,(int)hit.textureCoord.y);
		print(pixelColor.ToHexStringRGB());
	
	}
}

But every time I click on the texture my class returns the same color. And every time it’s a color that is not used in the texture.
It’s imported as advanced and read/write is enabled.
What’s going wrong ?

Texture coordinates are in the range of 0,0 to 1,1. Casting your texture coordinates to int means you’ll only ever get one of the corners of the texture.

Don’t cast to int and you should be fine. To fix that, change:

pixelColor = tex.GetPixel ((int)hit.textureCoord.x,(int)hit.textureCoord.y);

To

pixelColor = tex.GetPixel (hit.textureCoord.x,hit.textureCoord.y);

Looking at the documentation of RaycastHit.textureCoord you can see that the returned values range between 0 and 1.

To get the correct pixel position, you probably should multiply the x by the width and the y by the height like they do in the example.

Texture2D tex = rend.material.mainTexture as Texture2D;
Vector2 pixelUV = hit.textureCoord;
pixelUV.x *= tex.width;
pixelUV.y *= tex.height;

pixelColor = tex.GetPixel((int)pixelUV.x,(int)pixelUV.y);

Also, please note this sentence in the docs. Printing hit.textureCoord might help debug this futher to see if this applies to your case.

This can be used for 3D texture painting or drawing bullet marks. If the collider is no mesh collider, zero Vector2 will be returned.