截取指定相机的画面(PC)

为了方便起见,相机变量是直接public出来的。
脚本挂载上去之后直接把需要截图的相机拖拽上去。

图片的位置在Unity的StreamingAssets目录下的ScreenShot文件夹下,这个可自定义。
图片名字,第一张为0,依次累加。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Capture : MonoBehaviour
{
    public Camera camera;

    string folder = "ScreenshotFolder";
    int frameRate = 25;

    //文件命名时使用
    public int shot_Number;
    private string temp;

    //文件位置+名字
    private string filename;

    void Start()
    {
        //设置回放帧率(实时与游戏时间无关)
        Time.captureFramerate = frameRate;
        //创建文件夹
        System.IO.Directory.CreateDirectory(folder);
    }


    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            SaveFile();
        }
    }

   //设置图片位置
    void SetTexturePos()
    {
        temp = "/ScreenShot/";
        shot_Number += 1;
        string path = string.Format("{0:D4}{1:D2}.png", temp, (shot_Number).ToString());
        filename = Application.streamingAssetsPath + path;
    }

    //指定相机 截图
    void SaveFile()
    {
        
#if UNITY_EDITOR

        SetTexturePos();
#else
 
 
#if UNITY_ANDROID
		temp = "/ScreenShot/";
		string path  = string.Format ("{0:D4}{1:D2}.png", temp,shot_Number.ToString());
		filename = Application.persistentDataPath + path;
 
#endif
 
#if UNITY_IPHONE
		temp = "/Raw/ScreenShot/";
		string path  = string.Format ("{0:D4}{1:D2}.png", temp,shot_Number.ToString());
		filename = Application.temporaryCachePath + path;
 
#endif
 
#if UNITY_STANDALONE_WIN
		filename = "Screenshot.png";
#endif
#endif

      
        RenderTexture renderTexture;
        //深度问题depth
        renderTexture = new RenderTexture(Screen.width, Screen.height, 24);
        camera.targetTexture = renderTexture;
        camera.Render();

        Texture2D myTexture2D = new Texture2D(renderTexture.width, renderTexture.height);
        RenderTexture.active = renderTexture;
        myTexture2D.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0);
        myTexture2D.Apply();
        byte[] bytes = myTexture2D.EncodeToJPG();
        myTexture2D.Compress(true);
        myTexture2D.Apply();
        RenderTexture.active = null;

        SetTexturePos();

        System.IO.File.WriteAllBytes(filename, bytes);
        //Debug.Log (string.Format ("截屏了一张图片: {0}", filename));  
        Debug.Log("保存图片的路径" + filename);

        camera.targetTexture = null;
        GameObject.Destroy(renderTexture);

    }
}

使用方法:
调用函数ToScreenShot()

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值