How to capture and display a camera frame

Hi there, I am making this post to provide a clearer and simplified example for Camera.Render(). I looked around for examples of how to display one frame the camera has rendered, but all responses I found were convoluted, and the API for this subject is unnecessarily complicated.

RenderTexture CaptureCameraFrameTexture(Camera camera)
{
	// The camera needs to be disabled to use Render().
	camera.enabled = false;

	// There needs to be a RenderTexture object to pass to the camera, the construction shouldn't matter as the camera reassigns it, it just can't be null.
	RenderTexture capturedFrameTexture = new RenderTexture(Screen.width, Screen.height, depth: 32);

	// We giving the camera our capturedFrameTexture so it can be modified via Render().
	camera.targetTexture = PhotoFinishTexture;

	// We call Render() which renders this frame to the texture we passed to it.
	// NOTE: Render does not display anything to the screen, it is simply modifying the target texture.
	camera.Render();

	// Remove our texture from the targetTexture to prevent any overriding. 
	// This allows us to re-enable the camera while maintaining the captured frame on our texture (If so disired).
	camera.targetTexture = null;

	return capturedFrameTexture;
}

Modify or use the above code to simply get the Capture Frame data as a texture for us to use as we please. Now there are different suggestions online on how to get this to display on your screen, but I find the easiest way to go about this is to use Unity’s Gui.

void OnGUI()
{
	// You might want to declare rect once off as a property or in start instead.
	Rect textureRect = new Rect(x: 0, y: 0, Screen.width, Screen.height);

	// Use GUI.DrawTexture to apply the capture Frame texture to the screen
	GUI.DrawTexture(textureRect , PhotoFinishTexture);
}

This can be used on a camera that is enabled on awake. The camera just needs to be disabled before you use the Render() feature, and then afterward you can re-enable the camera. The captured frame texture will not be overwritten if you remove it from the camera.targetTexture.

1 Like