LoginSignup
3
2

More than 5 years have passed since last update.

Unityでカメラ入力が表示されないとき

Posted at

何故だ…

カメラの映像が真っ黒で何も表示されない。

解決方法

  • 存在するカメラ、0から全部試しましょう。

要するに

カメラのIDは0~あって、0番目は真っ黒な画しか出さない他のカメラだった。

LeapMotionのせいで0番目が真っ黒で小一時間悩んでしまった。
1番目にしたら無事表示された。なんだそんなことか。

PCでのテストとGearVRでのテストの差

スマホに出力するときはカメラ番号を変更しなければいけない。
"Leap"で除外するようにするか。

した。

カメラ入力表示スクリプト

WebCameraController.cs
using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class WebCameraController1    : MonoBehaviour {

    public int CamDeviceId = 0;
    public int Width = 1920;
    public int Height = 1080;
    public int FPS = 30;
    public float Alpha = 0.3f;


    void Start()
    {
        RawImage rawimage = this.GetComponents<RawImage>()[0];

        // get webCams
        WebCamDevice[] devices = WebCamTexture.devices;
        // display all cameras
        for (var i = 0; i < devices.Length; i++)
        {
            Debug.Log("["+ i +"]"+ devices[i].name); 
        }

        // LeapMotion skip
        if (devices[CamDeviceId].name == "Leap Dev Kit") CamDeviceId++;

        // set WebCamTexture
        if (devices.Length > 0 && CamDeviceId < devices.Length)
        {

            WebCamTexture webcamTexture = new WebCamTexture(devices[CamDeviceId].name, Width, Height, FPS);
            rawimage.texture = webcamTexture;
            rawimage.material.mainTexture = webcamTexture;
            rawimage.color = new Color(rawimage.color.r,
                rawimage.color.g,
                rawimage.color.b,
                Alpha);
            webcamTexture.Play();


        } else
        {
            Debug.Log("カメラが見つかりません。 "+ CamDeviceId+ "/ 0-" +(devices.Length-1));
            return;
        }

    }

    // Update is called once per frame
    void Update () {

    }
}

  • GameObject > UI > RawImageにこのスクリプトをアタッチ。
  • CamDeviceIdにカメラ番号をセット。ただし、LeapMotionのが見つかると飛ばされます。
  • Alphaは透明度0~1。0で完全透明。

これでPC・スマホを同じコードでカメラ表示できるようになった。
スマホ等で実行すると解像度に近いモノが選ばれるらしい?

参考資料

Unity画面にウェブカメラの画像を半透明で重ねて表示 | Psychic VRラボの殴り書き
大変参考にさせて頂きました。ありがとうございます。

3
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
3
2