前提・実現したいこと
Unity5.6.3で、ウェブカメラの映像をキャプチャし、生成したplaneにキャプチャした画像をテクスチャとして貼り付けたいです。
具体的にはHierarchyにあるWebCam(plane)にWebCamControllerコンポーネントを追加しています。
発生している問題・エラーメッセージ
問題は、WebCam(plane)に映像は出力されるのですが、スペースキーを押して生成されたCapturePanel(plane)のテクスチャが黒いことと、スペースキーを二回目に押すとエラーが2つ発生することです↓
Cannot get pixels when webcam is not running UnityEngine.WebCamTexture:GetPixels() WebCamController:Update() (at Assets/Scripts/WebCamController.cs:28) --------------------------------------------------------------------- Array size must be at least width*height UnityEngine.Texture2D:SetPixels(Color[]) WebCamController:SaveToTexture(Color[]) (at Assets/Scripts/WebCamController.cs:37) WebCamController:Update() (at Assets/Scripts/WebCamController.cs:28)
該当のソースコード
C#
1using System.Collections; 2using System.Collections.Generic; 3using UnityEngine; 4 5public class WebCamController : MonoBehaviour 6{ 7 int width = 1280; 8 int height = 720; 9 int fps = 30; 10 WebCamTexture webcamTexture; 11 public GameObject prefab; 12 public Vector3 position; 13 void Start() 14 { 15 WebCamDevice[] devices = WebCamTexture.devices; 16 webcamTexture = new WebCamTexture(devices[0].name, this.width, this.height, this.fps); 17 GetComponent<Renderer>().material.mainTexture = webcamTexture; 18 webcamTexture.Play(); 19 } 20 21 22 void Update() 23 { 24 if (Input.GetKeyUp(KeyCode.Space)) 25 { 26 if (webcamTexture != null) 27 { 28 SaveToTexture(webcamTexture.GetPixels()); 29 } 30 } 31 } 32 33 void SaveToTexture(Color[] texData) 34 { 35 Texture2D takenPhoto = new Texture2D(width, height, TextureFormat.ARGB32, false); 36 GameObject capture = Instantiate(prefab, position, Quaternion.identity); 37 takenPhoto.SetPixels(texData); 38 takenPhoto.Apply(); 39 capture.GetComponent<Renderer>().material.mainTexture = takenPhoto; 40 41 } 42}
試したこと
補足情報(FW/ツールのバージョンなど)
Unity5.6.3を使用しています。
あなたの回答
tips
プレビュー