unity擷取相機所看到的內容並儲存圖片
阿新 • • 發佈:2019-02-12
如題,需要將某個相機所看到的畫面儲存成圖片。
步驟大概是將相機看到的傳給rendertexture,然後傳給texture2d,然後儲存成圖片。
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraShoot : MonoBehaviour { Camera secondCam; // Use this for initialization void Start () { secondCam = GameObject.Find("Camera").GetComponent<Camera>(); } // Update is called once per frame void Update () { if (Input.GetKeyDown(KeyCode.Space)) { Fun(Camera.main,"MainCamera.png"); Fun(secondCam, "SecondCamera.png"); } } void Fun(Camera m_Camera,string filename) { RenderTexture rt = new RenderTexture(Screen.width, Screen.height, 16); m_Camera.targetTexture = rt; m_Camera.Render(); RenderTexture.active = rt; Texture2D t = new Texture2D(Screen.width, Screen.height); t.ReadPixels(new Rect(0, 0, t.width, t.height),0,0); t.Apply(); string path = Application.streamingAssetsPath + "/"+filename; System.IO.File.WriteAllBytes(path, t.EncodeToPNG()); } }
關於新建一個rendertexture時的depth引數,我不是很理解,看了看文件還是沒理解其中個別術語的意思。
反正填0,16,24/32
我試了試0的時候結果是沒有顯示3d物體的
其他數值可以。