Capturing A Camera Image In Unity

Code

        public Texture2D CaptureImage (Camera camera, int width, int height, Nullable<Quaternion> rotation = null, Nullable<Vector3> position = null)
        {
            Texture2D captured = new Texture2D (width, height);
            if (rotation != null)
            {
                camera.transform.rotation = rotation.Value;
            }
 
            if (position != null)
            {
                camera.transform.position = position.Value;
            }
 
            camera.Render();
            RenderTexture.active = camera.targetTexture;
            captured.ReadPixels(new Rect(0,0,width,height),0,0);
            captured.Apply();
            RenderTexture.active = null;
            return captured;
        }

Commentary

This method is a simple way of capturing the visible contents of a camera to a Texture2D. If you need to save snapshots or create dynamic textures at runtime this will do that.

Snippet Usage

Unless otherwise stated, the content of this page is licensed under GNU Free Documentation License.