Unity干中学——如何实现游戏截图?

时间:2022-06-06 19:52:21
 using UnityEngine;
using System.Collections;
using System.IO; public class ScreenShot : MonoBehaviour
{
// Use this for initialization
void Update()
{
if (Input.GetKey(KeyCode.LeftAlt) && Input.GetKeyDown(KeyCode.L))
{
StartCoroutine(CaptureScreen());
} } public IEnumerator CaptureScreen()
{
// 渲染完成之后在读取屏幕缓冲
yield return new WaitForEndOfFrame();
int width = Screen.width;
int height = Screen.height;
Texture2D tex = new Texture2D(width, height, TextureFormat.RGB24, false);//要保存图片的大小
//截取的区域
tex.ReadPixels(new Rect(, , width, height), , );
tex.Apply();
//把图片数据转换为byte数组
byte[] buffer = tex.EncodeToPNG();
Destroy(tex);
//然后保存为图片
File.WriteAllBytes(Application.persistentDataPath + "/" + System.DateTime.Now.ToFileTime() + ".png", buffer);
}
} 上面的代码参考了Unity的脚本手册,实现同时按下LeftAlt和L键进行屏幕截图。下一篇文章我将实现通知中心的功能,将截图完成的信息显示出来。