はじめに
とある事情でUSBカメラを複数台搭載したロボットの操縦用ソフトを作ったので,その際のメモを残しておく.
実行環境
- Unity2019.2.9f1
- Webカメラはlogicoolなど3台
要点
複数台といってもやることは1台の時と同じなのでWebCamTexure wct = WebCamTexture.devices[i]
のように,好きなインデックスのカメラを取得して表示すればよい.
以下は詳しい手順.
手順
前準備
とりあえず適当なプロジェクトを作成して立ち上げておく.そして,カメラの映像を映し出すためのPlaneオブジェクトを配置する.
描画用スクリプト
そして,配置したPlaneオブジェクトに今回使うスクリプト(ここではMultiCam.cs
とした)をアタッチする.
MultiCam.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MultiCam : MonoBehaviour
{
// Start is called before the first frame update
private WebCamTexture wct = null;//カメラのテクスチャ
private Renderer renderer; //Planeのテクスチャを書き換えるために使う
void Start()
{
//まずPlane自身のテクスチャ情報を扱えるようにRendererを取得しておく
this.renderer = this.GetComponent<Renderer>();
}
// Update is called once per frame
void Update()
{
//試しに3秒ごとにカメラを切り替えている
if (Time.frameCount % 180 == 0) this.SetCamera(Time.frameCount / 180);
}
private void SetCamera(int idx) {
// 現在接続中のカメラはWebCamTexture.devicesに格納されている.
// したがってLengthがカメラの台数となる
int len = WebCamTexture.devices.Length;
if(len == 0) return;
try {
wct.Stop();
} catch { }
this.wct = new WebCamTexture(WebCamTexture.devices[idx % len].name);
this.wct.Play();
this.renderer.material.mainTexture = this.wct;
}
}
実行すれば以下のような形でPlaneオブジェクト上に映像が投影される.
また,複数台設定されている場合は3秒ごとにカメラの映像が切り替わっていくはず.
スクリプトの概要
ざっとこんな感じの流れ.
- 再生中の
WebCamTexture
(この例ではwct
)をwct.Stop()
で停止させる.※wctがnullだとまずいのでtry-catchで挟んでいる -
wct
に対象のカメラのテクスチャを格納する. -
wct.Play()
で映像の再生を開始. - Planeオブジェクト自身のテクスチャ(この例では
renderer
)にwctをセットすることでPlane上に映像を映す.
最後に
実際の操縦用ソフトではUSBカメラの接続・切断を自動認識するように設計していた.
それについては次の記事に書きたい書いた.