Skip to content

Instantly share code, notes, and snippets.

@noshipu
Created April 29, 2017 02:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save noshipu/258fafa155768e285b1ad6566b8d5284 to your computer and use it in GitHub Desktop.
Save noshipu/258fafa155768e285b1ad6566b8d5284 to your computer and use it in GitHub Desktop.
OculusStore等で用意するスクリーンショットをUnityで撮るやつ
using System;
using System.IO;
using UnityEngine;
namespace ViRD.Tools
{
public class ScreenshotCapture : MonoBehaviour
{
private RenderTexture m_RenderTexture;
[SerializeField] private Camera m_Camera;
[SerializeField] private int m_Width = 2560;
[SerializeField] private int m_Height = 1440;
[SerializeField] private int m_Depth = 24;
[SerializeField] private RenderTextureFormat m_RenderTextureFormat = RenderTextureFormat.ARGB32;
// 撮影実行キー
[SerializeField] private KeyCode m_CaptureKeyCode = KeyCode.C;
void Start()
{
m_RenderTexture = new RenderTexture(m_Width, m_Height, m_Depth, m_RenderTextureFormat);
m_RenderTexture.Create();
// カメラを指定していない場合はメインカメラを参照
if(m_Camera == null)
{
m_Camera = Camera.main;
}
}
private void Update()
{
// 任意のキーで撮影する
if (Input.GetKeyDown(m_CaptureKeyCode))
{
CaptureImage();
}
}
// 撮影処理
public void CaptureImage()
{
if (!m_RenderTexture.IsCreated())
{
return;
}
// カメラにRenderTextureをセット
m_Camera.targetTexture = m_RenderTexture;
m_Camera.Render();
RenderTexture.active = m_RenderTexture;
// ファイルを保存
string fileName = string.Format("screenshot_{0}.png", DateTime.Now.ToString("yyyyMMddHHmmssfff"));
Texture2D texture = new Texture2D(m_RenderTexture.width, m_RenderTexture.height, TextureFormat.RGB24, false, false);
texture.ReadPixels(new Rect(0, 0, m_RenderTexture.width, m_RenderTexture.height), 0, 0);
texture.Apply();
// NOTE: とりあえずAssetsの下に保存している
File.WriteAllBytes(Application.dataPath + "/" + fileName, texture.EncodeToPNG());
Debug.Log(string.Format("{0}に保存しました", Application.dataPath + "/" + fileName));
// RenderTextureを解除
if (m_Camera == Camera.main)
{
Camera.main.targetTexture = null;
}
RenderTexture.active = null;
}
}
}
@noshipu
Copy link
Author

noshipu commented Apr 29, 2017

  • 使い方
  1. ScreenshotCapture.csを任意のオブジェクトにアタッチ
  2. 撮影用のカメラを配置(メインカメラの子供とかに配置するのが望ましいかも)
  3. アプリを実行
  4. 任意のタイミングで撮影キーを押す(デフォルトはcキー)
  5. Assetsの直下にスクリーンショットが生成されていることを確認する

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment