Making textures from screen content

If you want your game or player to take in-game snapshots and apply them as textures, this recipe will show you how. This can be very useful if you plan to implement an in-game photo gallery or display a snapshot of a past key moment at the end of a level (racing games and stunt simulations use this feature a lot). For this particular example, we will take a snapshot from within a framed region of the screen and print it on the top-right corner of the display.

Getting ready

For this recipe, we have prepared the BasicScene Unity package, containing a scene named BasicScene. The package is in the 1362_05_codes folder.

How to do it...

To create textures from screen content, follow these steps:

  1. Import the BasicScene package into a new Project.
  2. From the Project view, open the BasicScene level. This is a basic scene featuring an animated character and some extra geometry. It also features a Canvas for UI elements.
  3. Create an UI Image GameObject from the Create drop-down menu on top of the Hierarchy view (Create | UI | Image). Please note that it will be created as a child of the Canvas GameObject. Then, rename it frame.
  4. From the Inspector view, find the Image (Script) component of the frame GameObject and set InputFieldBackground as its Source Image. This is a sprite that comes bundled with Unity, and it's already sliced for resizing purposes.
  5. Now, from the Inspector view, change Rect Transform to the following values: Anchors | Min | X: 0.25, Y: 0.25; Anchors | Max | X: 0.75, Y: 0.75; Pivot | X: 0.5, Y: 0.5; Left: 0; Top: 0; Pos Z: 0; Right: 0; Bottom: 0.
  6. From the Image (Script) component, uncheck the Fill Center option, as shown below:
    How to do it...
  7. Create an UI Raw Image GameObject from the Create drop-down menu on top of the Hierarchy view (Create | UI | RawImage). Please note that it will be created as a child of the Canvas GameObject. Then, rename it Photo.
  8. From the Inspector view, find the Raw Image (Script) component of the Photo GameObject and set None as its Texture. Also, from the top of the Inspector view, disable the Photo GameObject by unchecking the box on the side of its name.
  9. Now, from the Inspector view, change the Rect Transform to the following values: Width: 1; Height: 1; Anchors | Min | X: 0, Y: 1; Anchors | Max | X: 0, Y: 1; Pivot | X: 0, Y: 1; Pos X: 0; Pos Y: 0; Pos Z: 0 as shown in the following screenshot:
    How to do it...
  10. We need to create a script. In the Project view, click on the Create drop-down menu and choose C# Script. Rename it ScreenTexture and open it in your editor.
  11. Open your script and replace everything with the following code:
    using UnityEngine;
    using UnityEngine.UI;
    using System.Collections;
    
    public class ScreenTexture : MonoBehaviour {
      public GameObject photoGUI;
      public GameObject frameGUI;
      public float ratio = 0.25f;
    
      void  Update (){
        if (Input.GetKeyUp (KeyCode.Mouse0))
          StartCoroutine(CaptureScreen());
      }
    
      IEnumerator  CaptureScreen (){
        photoGUI.SetActive (false);
        int sw = Screen.width;
        int sh = Screen.height;
        RectTransform frameTransform = frameGUI.GetComponent<RectTransform> ();
        Rect framing = frameTransform.rect;
        Vector2 pivot = frameTransform.pivot;
        Vector2 origin = frameTransform.anchorMin;
        origin.x *= sw;
        origin.y *= sh;
        float xOffset = pivot.x * framing.width;
        origin.x += xOffset;
        float yOffset = pivot.y * framing.height;
        origin.y += yOffset;
        framing.x += origin.x;
        framing.y += origin.y;
        int textWidth = (int)framing.width;
        int textHeight = (int)framing.height;
        Texture2D texture = new Texture2D(textWidth,textHeight);
        yield return new WaitForEndOfFrame();
        texture.ReadPixels(framing, 0, 0);
        texture.Apply();
        photoGUI.SetActive (true);
        Vector3 photoScale = new Vector3 (framing.width * ratio, framing.height * ratio, 1);
        photoGUI.GetComponent<RectTransform> ().localScale = photoScale;
        photoGUI.GetComponent<RawImage>().texture = texture;
      }
    }
  12. Save your script and apply it to the Main Camera GameObject within the Multipurpose Camera Rig | Pivot GameObject.
  13. In the Inspector view, find the Screen Texture component and populate the fields Photo GUI and Frame GUI with the GameObjects Photo and frame respectively:
    How to do it...
  14. Play the scene. You will be able to take a snapshot of the screen (and have it displayed in the top-left corner at a quarter of the original size) by clicking the mouse button, as shown in the following screenshot:
    How to do it...

How it works...

First, we created a GUI frame from which to take a snapshot and a GUI element onto which to apply the texture. Then, we applied a script to the Main Camera to capture the screen content and apply a new texture to it.

The script creates a new texture and captures the left mouse button being pressed, whereupon it starts a coroutine to calculate a Rect area, copy screen pixels from that area, and apply them to a texture to be displayed by the photo GUI element, which is also resized to fit the texture.

The size of the Rect is calculated from the screen's dimensions and the frame's Rect Transform settings, particularly its Pivot, Anchors, Width, and Height. The screen pixels are then captured by the ReadPixels() command, and applied to the texture, which is then applied to the Raw Image photo, which is resized to meet the desired ratio between the photo size and the original pixels.

There's more...

Apart from displaying the texture as a GUI element, you can use it in other ways.

Applying your texture to a material

You can apply your texture to an existing object's material by adding a line similar to GameObject.Find("MyObject").renderer.material.mainTexture = texture; to the end of the CaptureScreen function.

Using your texture as a screenshot

You can encode your texture as a PNG image file and save it. Check out Unity's documentation on this feature at http://docs.unity3d.com/Documentation/ScriptReference/Texture2D.EncodeToPNG.html.

See also

  • The Saving screenshots from the game recipe in Chapter 10, Working with the External Resource Files and Devices
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.172.115