【基础】Unity截图时只截取场景内容

Unity游戏截图技巧
本文介绍了一个Unity游戏截图的方法,该方法能够排除UI元素,仅截取游戏场景内容。通过使用RenderTexture和Texture2D,可以捕获指定Camera的视图,并将其保存为PNG文件。此外还提供了一个更简单的解决方案,通过临时修改UI Camera的裁剪掩码。

在游戏截屏时,我们需要只截取场景内容,而不包括NGUI控件,实现脚本如下(只截取gameCamera和bgCamera中的内容):

using UnityEngine;
using System.Collections;

public class CaptureTest : MonoBehaviour {
    public Camera gameCamera;
    public Camera bgCamera;
    // Use this for initialization
    void Start () {
    
    }
    
    // Update is called once per frame
    void Update () {
    
    }

    void OnClick()
    {
        Rect rect=new Rect(0,0,Screen.width,Screen.height);
        CaptureCamera(gameCamera, bgCamera, rect);
    }
    Texture2D CaptureCamera(Camera gameCamera,Camera bgCamera, Rect rect)
    {
        // 创建一个RenderTexture对象,最后的depth得根据要截取的场景的depth最高来定,如果最高是0,那么这里最后的0改成1,保证截取的时候depth大于要截取的所有camera
        RenderTexture rt = new RenderTexture((int)rect.width, (int)rect.height, 0);
        // 设置两个camera的targetTexture
        gameCamera.targetTexture = rt;
        bgCamera.targetTexture = rt;
       //注意渲染顺序
        bgCamera.Render();
        gameCamera.Render();
   
        // 激活这个rt, 并从中中读取像素。
        RenderTexture.active = rt;
        Texture2D screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGB24, false);
        screenShot.ReadPixels(rect, 0, 0);// 注:这个时候,它是从RenderTexture.active中读取像素
        screenShot.Apply();

        // 重置相关参数,以使用camera继续在屏幕上显示
        gameCamera.targetTexture = null;
        bgCamera.targetTexture = null;
        //ps: camera2.targetTexture = null;
        RenderTexture.active = null; // JC: added to avoid errors
        GameObject.Destroy(rt);
        // 最后将这些纹理数据,成一个png图片文件
        byte[] bytes = screenShot.EncodeToPNG();
        string filename = Application.dataPath + "/Screenshot.png";
        System.IO.File.WriteAllBytes(filename, bytes);
        Debug.Log(string.Format("截屏了一张照片: {0}", filename));

        return screenShot;
    }
}

 当然如果不介意屏幕上的GUI元素消失一小会,也可以简单的用以下方式:

int PrevMask = uiCamera.cullingMask;
uiCamera.cullingMask = 0;
Application.CaptureScreenshot("screenshot.png", 0);
//等待一定时间,可以用WaitForFixedUpdate或者WaitForSeconds,让截图完成
uiCamera.cullingMask = PrevMask;

 

转载于:https://www.cnblogs.com/cowill/p/4264255.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值