Hey,
This is my first post so I hope it’s in the correct location.
I’ve searched all over the internet and I can’t find exactly what I’m looking for or I’m not implementing it correctly.
I want to be able to click on objects in the scene and get the color of the pixel in the texture assigned to the object I click in 3D. I don’t need to take into account shadows or anything, just the texture info. I can get it to work fine with a cube but I’m having issues with cylinders and spheres. I’m looking for a solution to eventually work on any shape, even prefabs.
My Code (essentially copied from other solutions):
void SomeFunction()
{
RaycastHit hit;
Ray theRay = Camera.main.ScreenPointToRay(Input.mousePosition);
if(!Input.GetMouseButtonDown(0))
return;
Debug.Log ("Testing");
if(!Physics.Raycast (theRay,out hit))
return;
Debug.Log ("A Hit " + hit.transform.position);
Renderer rend = hit.transform.GetComponent<Renderer>();
Texture2D tex = rend.material.mainTexture as Texture2D;
Vector2 pixelUV = hit.textureCoord;
Debug.Log (pixelUV);
pixelUV.x *= rend.material.mainTexture.width;
pixelUV.y *= rend.material.mainTexture.height;
Debug.Log (tex.GetPixel((int)pixelUV.x,(int)pixelUV.y));
}
Line 20 - Debug.Log (pixelUV)
Always returns (0.0, 0.0) for the Sphere and only works for the top and bottom of the cylinder.
My thought is that it has to do with how textures get “wrapped” around the sphere based on each polygon it consists of. I hope it’s something simple I’m just missing.
Thank you very much