Search Unity

screenShot to sprite

Discussion in '2D' started by jimmyo, Jun 1, 2014.

  1. jimmyo

    jimmyo

    Joined:
    Mar 20, 2014
    Posts:
    20
    I am creating a fairly complex programmatic gameboard using multiple gameObjects, sprites, materials, etc. Once it is created it is static so I want to take a screenshot photo of the gameboard and convert that to a single sprite -- goal is to save on draw calls, move it around and scale it cleanly (eg in a menu), etc.

    My work flow is:
    1. set up the gameboard
    2. use ReadPixels to take the screenshot into a Texture2D
    3. use Sprite.Create() to display the image using a single new gameObject
    4. kill all the previous gameObjects

    Everything is working, EXCEPT that the image that is created is scaled smaller than the original screen. I can't figure out why the image is a shrunken version of the original screen. I want a 1 for 1 pixel for pixel representation in my sprite.

    Thank you in advance for any ideas as to why this shrinking is happening?

    Relevant code is below:

    In a class attached to camera:
    Code (csharp):
    1.  
    2. public class TakeScreenShot : MonoBehaviour {
    3.  
    4.     public static int snapPhoto = 0;
    5.     public static Texture2D image;
    6.  
    7.     IEnumerator OnPostRender () {
    8.         if (snapPhoto==1) {
    9.             yield return new WaitForEndOfFrame();
    10.             image = new Texture2D(Screen.width,Screen.height,TextureFormat.RGB24,false);
    11.             image.ReadPixels(new Rect(0,0,Screen.width,Screen.height),0,0,false);
    12.             image.Apply();
    13.             snapPhoto = 2;
    14.         }
    15.     }
    16. }
    17.  
    In main in Update():
    Code (csharp):
    1.  
    2. if (Input.GetMouseButtonDown(0)) {
    3.     TakeScreenShot.snapPhoto = 1;
    4. }
    5.  
    6. if (TakeScreenShot.snapPhoto == 2) {
    7.     TakeScreenShot.snapPhoto = 0;
    8.     GameObject go = new GameObject();
    9.            
    10.     SpriteRenderer sr = go.AddComponent<SpriteRenderer>();
    11.     sr.sprite = Sprite.Create(TakeScreenShot.image,new Rect(0,0,Screen.width,Screen.height),new Vector2(0,0));
    12.     Vector3 gotrlp = go.GetComponent<Transform>().localPosition;
    13.     gotrlp.x = -2f; //set this to bottom left of screen so that whole image can be displayed
    14.     gotrlp.y = -2f; //set this to bottom left of screen so that whole image can be displayed
    15.     go.GetComponent<Transform>().localPosition = gotrlp;
    16. }
    17.