首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >【Unity3D日常开发】(二十二)Unity3D进行截图

【Unity3D日常开发】(二十二)Unity3D进行截图

作者头像
玖柒的小窝
修改2021-10-25 10:29:56
修改2021-10-25 10:29:56
43300
代码可运行
举报
文章被收录于专栏:各类技术文章~各类技术文章~
运行总次数:0
代码可运行

一、前言

来看一下怎么截图的吧

二、效果

三、代码

代码语言:javascript
代码运行次数:0
运行
复制
using UnityEngine;

public class Screenshot : MonoBehaviour
{
    //截图相机
    Camera capCamera;
    //保存图片
    Texture2D screenShot;

    void Start()
    {
        capCamera = GameObject.Find("Main Camera").GetComponent<Camera>();
    }

    void OnGUI()
    {
        if (GUILayout.Button("Show"))
        {
            CaptureCamera();
        }
    }

    void CaptureCamera()
    {
        Rect rect = new Rect(Screen.width * 0f, Screen.height * 0f, Screen.width * 1f, Screen.height * 1f);
        // 创建一个RenderTexture对象  
        RenderTexture rt = new RenderTexture((int)rect.width, (int)rect.height, 0);
        // 临时设置相关相机的targetTexture为rt, 并手动渲染相关相机  
        capCamera.targetTexture = rt;
        capCamera.Render();
        // 激活这个rt, 并从中中读取像素。  
        RenderTexture.active = rt;
        screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGB24, false);
        //从RenderTexture.active中读取像素
        screenShot.ReadPixels(rect, 0, 0);
        screenShot.Apply();

        // 重置相关参数,以使用camera继续在屏幕上显示  
        capCamera.targetTexture = null;
        //避免重复添加的错误
        RenderTexture.active = null; 

        //销毁这个对象
        Destroy(rt);

        //保存图片
        byte[] bytes = screenShot.EncodeToPNG();
        string filename = Application.streamingAssetsPath + "/2.png";
        System.IO.File.WriteAllBytes(filename, bytes);
    }
}

本文系转载,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文系转载前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一、前言
  • 二、效果
  • 三、代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档