うにてぃブログ

主にUnityとC#に関する記事を書いていきます

【Unity】ハードウェア上の Camera を使う

MacのUnity上で利用することのみの想定なので、AndroidiOSなどでは権限を追加しないと動作しません

Unity で カメラを使うには WebCamTexture クラスを利用すればできるようです

UnityEngine.WebCamTexture - Unity スクリプトリファレンス

テスト

WebCamTexture のインスタンスを作成し Play を呼ぶだけだったので簡単にカメラが利用できました
AndroidiOSなどではインカメラ・アウトカメラの違いや、カメラを回転しないといけない場合があります

using System;
using UnityEngine;
using UnityEngine.UI;
 
public class CameraSample : MonoBehaviour
{
    [SerializeField]
    private RawImage _rawImage;
    private WebCamTexture _webCamTexture;
 
    private void Start()
    {
        PlayCamera();
    }
 
    /// <summary>
    /// カメラを起動する
    /// </summary>
    private void PlayCamera()
    {
        try
        {
            StopCamera();
            var cameraDevice = WebCamTexture.devices[0];
            var cameraImageSize = ((RectTransform) _rawImage.transform).sizeDelta;
            _webCamTexture = new WebCamTexture(
                cameraDevice.name,
                (int) cameraImageSize.y,
                (int) cameraImageSize.x,
                30);

            _rawImage.material.mainTexture = _webCamTexture;
            _webCamTexture.Play();
        }
        catch (Exception e)
        {
            Debug.LogError(e.Message + "\n" + e.StackTrace);
            throw;
        }
    }
 
    /// <summary>
    /// カメラを停止する
    /// </summary>
    private void StopCamera()
    {
        if (_webCamTexture == null)
            return;
 
        _webCamTexture.Stop();
        Destroy(_webCamTexture);
        _webCamTexture = null;
    }
}

f:id:hacchi_man:20200326000608p:plain