1
2

More than 3 years have passed since last update.

Unityで複数台のWebカメラを表示する

Last updated at Posted at 2020-06-13

はじめに

とある事情で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秒ごとにカメラの映像が切り替わっていくはず.

スクリプトの概要

ざっとこんな感じの流れ.

  1. 再生中のWebCamTexture(この例ではwct)をwct.Stop()で停止させる.※wctがnullだとまずいのでtry-catchで挟んでいる
  2. wctに対象のカメラのテクスチャを格納する.
  3. wct.Play()で映像の再生を開始.
  4. Planeオブジェクト自身のテクスチャ(この例ではrenderer)にwctをセットすることでPlane上に映像を映す.

最後に

実際の操縦用ソフトではUSBカメラの接続・切断を自動認識するように設計していた.
それについては次の記事書きたい書いた.

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2