前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >玩游戏想记录一下自己超神的瞬间?那么就来看一下如何使用Unity截图吧

玩游戏想记录一下自己超神的瞬间?那么就来看一下如何使用Unity截图吧

作者头像
恬静的小魔龙
发布2022-08-07 09:01:38
2490
发布2022-08-07 09:01:38
举报
文章被收录于专栏:Unity3DUnity3D

一、前言

来看一下怎么截图的吧

二、效果

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

三、代码

代码语言:javascript
复制
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);
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021-06-25,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

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

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

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