为了方便起见,相机变量是直接public出来的。
脚本挂载上去之后直接把需要截图的相机拖拽上去。
图片的位置在Unity的StreamingAssets目录下的ScreenShot文件夹下,这个可自定义。
图片名字,第一张为0,依次累加。
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);
}
}
使用方法:
调用函数ToScreenShot()