unity3d 截屏幕图片代码
时间: 2023-07-09 10:36:52 浏览: 50
在 Unity3D 中,可以使用以下代码来截取屏幕图片:
```csharp
public class ScreenShot : MonoBehaviour {
// 设置截图的宽度和高度
public int width = 1920;
public int height = 1080;
// 截图函数
public void CaptureScreen() {
// 创建一张空的纹理
Texture2D tex = new Texture2D(width, height, TextureFormat.RGB24, false);
// 读取屏幕像素到纹理中
tex.ReadPixels(new Rect(0, 0, width, height), 0, 0);
// 应用像素到纹理中
tex.Apply();
// 将纹理转换为PNG格式的字节数组
byte[] bytes = tex.EncodeToPNG();
// 保存字节数组为文件
File.WriteAllBytes(Application.dataPath + "/../Screenshot.png", bytes);
}
}
```
在上述代码中,我们首先创建了一个空的纹理,然后使用`ReadPixels`函数将屏幕像素读取到纹理中,并使用`Apply`函数将像素应用到纹理中。最后,我们将纹理转换为PNG格式的字节数组,并使用`File.WriteAllBytes`函数保存为文件。可以在需要的地方调用`CaptureScreen`函数来进行截图操作。