Search code examples
imageunity-game-enginecameracropunityscript

Switch device camera in Unity 3d


I am using WebCamTexture class to open camera from device. I want to switch camera from front to back and vice versa in between the game play. Can anybody help?

    WebCamDevice[] devices = WebCamTexture.devices;
    WebCamTexture   webCamTexture = new WebCamTexture(devices[1].name);
    renderer.material.mainTexture = webCamTexture;
    webCamTexture.filterMode = FilterMode.Trilinear;
    webCamTexture.Play();

This opens my front camera. But I can't switch the camera.


Solution

  • I got the solution. You just need to set the name of the device. By default back camera is "Camera 0" and "Camera 1" front camera. First Stop your camera , change the set device.

    if (devices.Length > 1) {
             webCamTexture.Stop();
            if (frontCamera == true)
            {
                webCamTexture.deviceName = devices[0].name;
                frontCamera = false;
            }
            else
            {
                webCamTexture.deviceName = devices[1].name;
                frontCamera = true;
            }
             webCamTexture.Play ();
        }