using UnityEngine;
using System.Collections;
public class HiResScreenshots : MonoBehaviour
{
public Camera camera;
public int resWidth = 2550;
public int resHeight = 3300;
private bool takeHiResShot = false;
public static string ScreenShotName(int width, int height)
{
return string.Format("{0}/screenshots/screen_{1}x{2}_{3}.png",
Application.dataPath,
width, height,
System.DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss"));
}
public void TakeHiResShot()
{
takeHiResShot = true;
}
void LateUpdate()
{
takeHiResShot |= Input.GetKeyDown("k");
if (takeHiResShot)
{
RenderTexture rt = new RenderTexture(resWidth, resHeight, 24);
camera.targetTexture = rt;
Texture2D screenShot = new Texture2D(resWidth, resHeight, TextureFormat.RGB24, false);
camera.Render();
RenderTexture.active = rt;
screenShot.ReadPixels(new Rect(0, 0, resWidth, resHeight), 0, 0);
camera.targetTexture = null;
RenderTexture.active = null; // JC: added to avoid errors
Destroy(rt);
byte[] bytes = screenShot.EncodeToPNG();
string filename = ScreenShotName(resWidth, resHeight);
System.IO.File.WriteAllBytes(filename, bytes);
Debug.Log(string.Format("Took screenshot to: {0}", filename));
takeHiResShot = false;
}
}
}
我收到异常 DirectoryNotFoundException,当按一次 k 键时,它会不停地截取屏幕截图,我希望每次按 k 键时它都截取一张屏幕截图。
我收到异常 DirectoryNotFoundException
您可以使用Path.GetDirectoryName
来获取完整的目录路径,但不包含filename
.
然后你可以简单地使用 Directory.CreateDirectory
在指定路径中创建所有目录和子目录,除非它们已经存在。
So.you 甚至不必检查它是否存在。(当然,您仍然需要获得许可才能这样做)
按一次 k 键时,它会不停地截取屏幕截图,我希望每次按 k 键时它都截取一张屏幕截图。
这是一个后续错误。由于您遇到异常,您永远不会到达该行
takeHiResShot = false;
一般来说,不如在这里使用协程,例如
public void TakeHiResShot()
{
StartCoroutine (ScreenshotRoutine ());
}
void Update()
{
if(Input.GetKeyDown("k"))
{
StartCoroutine (ScreenshotRoutine ());
}
}
private IEnumerator ScreenshotRoutine ()
{
yield return new WaitForEndOfFrame();
var rt = new RenderTexture(resWidth, resHeight, 24);
camera.targetTexture = rt;
var screenShot = new Texture2D(resWidth, resHeight, TextureFormat.RGB24, false);
camera.Render();
RenderTexture.active = rt;
screenShot.ReadPixels(new Rect(0, 0, resWidth, resHeight), 0, 0);
camera.targetTexture = null;
RenderTexture.active = null; // JC: added to avoid errors
Destroy(rt);
var bytes = screenShot.EncodeToPNG();
var filename = ScreenShotName(resWidth, resHeight);
var directory = Path.GetDirectoryName(filename);
Directory.CreateDirectory(directory);
System.IO.File.WriteAllBytes(filename, bytes);
Debug.Log($"Took screenshot to: /"{filename}/"", this);
}
这使得在出现错误的情况下不可能陷入无限循环
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句