上代码(https://blog.csdn.net/anyuanlzh/article/details/17008909这个链接的总结更为全面)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
public class MyShot : MonoBehaviour
{
public Texture2D texture2d;
public bool isShoot;
// Start is called before the first frame update
void Start()
{
texture2d = new Texture2D(256,256,TextureFormat.RGB24,false);
}
// Update is called once per frame
void Update()
{
if(Input.GetMouseButtonDown(0))
{
StartCoroutine(CaptrueScreenShoot()); //得写成延迟,因为必须用到语句yield return new WaitForEndOfFrame();
}
}
void OnGUI()
{
if(isShoot)
{
GUI.DrawTexture(new Rect(0, 0, 100, 100), texture2d, ScaleMode.StretchToFill);//GUI坐标系 坐标原点是屏幕左上角
//isShoot = false;
}
}
IEnumerator CaptrueScreenShoot()
{
//只在每一帧渲染完成后才读取屏幕信息(必须)
yield return new WaitForEndOfFrame();
//读取屏幕像素信息并存储为纹理数据
//texture2d.ReadPixels(new Rect(0, 0, 256, 256), 0, 0);//Texture2D用的是“屏幕坐标系”,坐标原点是屏幕左下角
texture2d.ReadPixels(new Rect(Screen.width/2-128,Screen.height/2-128,256,256),0,0);//屏幕正中256*256的区域
texture2d.Apply();
读取将这些纹理数据,成一个png图片文件
//byte[] bytes = texture2d.EncodeToPNG();
//string filename = Application.dataPath + "/" + "Show.png";
写入文件
//File.WriteAllBytes(filename, bytes);
//设置成可显示
isShoot = true;
}
}