If I now have the mouse position (x,y) int the screen,anyone tells me how to get the pixel rgb at the position?
Use a rendertexture on your main camera, then read the pixel color with Texture2D.GetPixel
use a rendertexture on the camera ??? what does it mean???
Please note that RenderTextures are a Pro Only feature.
Other than using a RenderTexture, you could capture a screenshot of the camera view, and then find the right pixel. Though consider that it’s quite expensive, so you won’t be able to do it every frame while maintaining a smooth framerate.
screenshot???how to capture it ?
Texture2D GetScreenshot( bool argb32 )
{
Rect viewRect = Camera.main.pixelRect;
Texture2D tex = new Texture2D( (int)viewRect.width, (int)viewRect.height, ( argb32 ? TextureFormat.ARGB32 : TextureFormat.RGB24 ), false );
tex.ReadPixels( viewRect, 0, 0, false );
tex.Apply( false );
return tex;
}
Thanks for that, here’s an update to this thread, because the unity get screenshot example is abit outdated, here is a version:
if (GUI.Button(Rect(160,120,150,20),“screentest”))
{
// Make a new texture of the right size and
// read the camera image into it.
var tex = new Texture2D(Screen.width, Screen.height);
tex.ReadPixels(new Rect(0, 0, 128, 128), 0, 0);
tex.Apply();
// Set the display texture to the newly captured image.
//display.material.mainTexture = tex;
// Reset the grab variable to avoid making multiple
// captures.
}
it’s unfinished cos i just realised in need the texture color not the ambient lighting+texturecolor,but it compiles.
this is a complete version:
code doesnt work on this forum for me at the moment…
press middle mouse button it will print the color at the screenpoint.
#pragma strict
var tex : Texture2D;
var mpos : Vector3;
function Update () {
if (Input.GetMouseButtonDown(2)) { moonrake();}
// print (Input.mousePosition);
}
function moonrake (){
mpos = Input.mousePosition;
var ray = Camera.main.ScreenPointToRay (mpos);
var cube : GameObject = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube.transform.localScale = Vector3(20, 20, 1);
cube.transform.position = Vector3(0, 0.5, 0);
cube.transform.LookAt(camera.main.transform,Vector3.up);
Destroy (cube.renderer.material);
// Application.CaptureScreenshot("Assets/savedmeshes/assets/ " + "Screenshot2.png");
sshot();
}
function sshot()//:Texture2D
{
// Make a new texture of the right size and
// read the camera image into it.
var tex = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false);
yield WaitForEndOfFrame();
tex.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);
tex.Apply();
var bla = tex.GetPixel ( mpos.x, mpos.y );
print(bla);
//Destroy (tex);
//return tex;
}