1
\$\begingroup\$

I'm trying to run a script that will display video from my webcam on my computer, but when I run it the error unable to find back camera pops up.

My webcam is hooked up and working, so as my other script, but this one doesn't do what I need it to do.

How can I fix this?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class MainCam : MonoBehaviour
{
    private bool camAvailable;
    private WebCamTexture backCam;
    private Texture defaultBackground;

    public RawImage background;
    public AspectRatioFitter fit;

    private void Start()
    {
        defaultBackground = background.texture;
        WebCamDevice[] devices = WebCamTexture.devices;

        if (devices.Length == 0)
        {
            Debug.Log("No camera detected");
            camAvailable = false;
            return;
        }

        for (int i = 0; i < devices.Length; i++)
        {
            if (!devices[i].isFrontFacing)
            {
                backCam = new WebCamTexture(devices[i].name, Screen.width, Screen.height);
            }
        }

        if (backCam == null)
        {
            Debug.Log("Unable to find back camera");
            return;
        }

        backCam.Play();
        background.texture = backCam;

        camAvailable = true;
    }

    private void Update()
    {
        if (!camAvailable)
            return;

        float ratio = (float)backCam.width / (float)backCam.height;
        fit.aspectRatio = ratio;

        float scaleY = backCam.videoVerticallyMirrored ? -1f: 1f;
        background.rectTransform.localScale = new Vector3(1f, scaleY, 1f);

        int orient = -backCam.videoRotationAngle;
        background.rectTransform.localEulerAngles = new Vector3(0, 0, orient);
    }
}
\$\endgroup\$
  • \$\begingroup\$ Why are you looking for a "back" camera on a PC? Wouldn't we expect PC webcams to generally be forward-facing? \$\endgroup\$ – DMGregory Feb 11 at 12:40
  • \$\begingroup\$ Can you confirm that you have at least one back facing camera in the list? A simple Debug.Log inside if (!devices[i].isFrontFacing) body should do the trick. \$\endgroup\$ – S. Tarık Çetin Feb 15 at 23:17

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Browse other questions tagged or ask your own question.