Take a screenshot of the specified camera (PC)

For convenience, camera variables are directly public.
After the script is mounted, directly drag and drop the camera that needs to be taken.

The location of the picture is in the ScreenShot folder under the StreamingAssets directory of Unity. This can be customized.
The name of the picture, the first one is 0, which are added up in sequence.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Capture : MonoBehaviour
{
    
    
    public Camera camera;

    string folder = "ScreenshotFolder";
    int frameRate = 25;

    //文件命名时使用
    public int shot_Number;
    private string temp;

    //文件位置+名字
    private string filename;

    void Start()
    {
    
    
        //设置回放帧率(实时与游戏时间无关)
        Time.captureFramerate = frameRate;
        //创建文件夹
        System.IO.Directory.CreateDirectory(folder);
    }


    void Update()
    {
    
    
        if (Input.GetKeyDown(KeyCode.Space))
        {
    
    
            SaveFile();
        }
    }

   //设置图片位置
    void SetTexturePos()
    {
    
    
        temp = "/ScreenShot/";
        shot_Number += 1;
        string path = string.Format("{0:D4}{1:D2}.png", temp, (shot_Number).ToString());
        filename = Application.streamingAssetsPath + path;
    }

    //指定相机 截图
    void SaveFile()
    {
    
    
        
#if UNITY_EDITOR

        SetTexturePos();
#else
 
 
#if UNITY_ANDROID
		temp = "/ScreenShot/";
		string path  = string.Format ("{0:D4}{1:D2}.png", temp,shot_Number.ToString());
		filename = Application.persistentDataPath + path;
 
#endif
 
#if UNITY_IPHONE
		temp = "/Raw/ScreenShot/";
		string path  = string.Format ("{0:D4}{1:D2}.png", temp,shot_Number.ToString());
		filename = Application.temporaryCachePath + path;
 
#endif
 
#if UNITY_STANDALONE_WIN
		filename = "Screenshot.png";
#endif
#endif

      
        RenderTexture renderTexture;
        //深度问题depth
        renderTexture = new RenderTexture(Screen.width, Screen.height, 24);
        camera.targetTexture = renderTexture;
        camera.Render();

        Texture2D myTexture2D = new Texture2D(renderTexture.width, renderTexture.height);
        RenderTexture.active = renderTexture;
        myTexture2D.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0);
        myTexture2D.Apply();
        byte[] bytes = myTexture2D.EncodeToJPG();
        myTexture2D.Compress(true);
        myTexture2D.Apply();
        RenderTexture.active = null;

        SetTexturePos();

        System.IO.File.WriteAllBytes(filename, bytes);
        //Debug.Log (string.Format ("截屏了一张图片: {0}", filename));  
        Debug.Log("保存图片的路径" + filename);

        camera.targetTexture = null;
        GameObject.Destroy(renderTexture);

    }
}

How to use:
call the function ToScreenShot()

Guess you like

Origin blog.csdn.net/qq_22975451/article/details/113189710