Search code examples
c#androidunity-game-engineandroid-camera

how to select front camera from device in Unity


Well, i'm fairly new to unity and a real noob in what's about textures, but i managed to use a device's camera (using the code at the end of this post)

The problem is that I'd like to use the front camera when using smartphone devices. Is there a noob way to do it?

Thanks for your attention, time and help <3

using UnityEngine;
using UnityEngine.UI;

public class CameraScript : MonoBehaviour
{
    static WebCamTexture backCam;

    void Start()
    {
        if (backCam == null)
            backCam = new WebCamTexture();

        GetComponent<Renderer>().material.mainTexture = backCam;

        this.GetComponent<RawImage>().material = this.GetComponent<SpriteRenderer>().material;

        if (!backCam.isPlaying)
            backCam.Play();

    } 
}

Solution

  • This is how you use the front facing camera in Unity:

    public class CameraScript : MonoBehaviour
    {    
        WebCamTexture = null;
    
        void Start()
        {
           WebCamDevice[] devices = WebCamTexture.devices;
    
           foreach (var device in devices) {
             if (device.isFrontFacing) {
               webCamTexture = new WebCamTexture(device.name);
             }
           }
     
           if (webCamTexture == null) {
             webCamTexture = new WebCamTexture();
           }
        }
    }
    

    If no front facing camera is available then WebCamDevice defaults to an empty constructor WebCamTexture in the example I have provided.

    It's good to refer to the Unity Documentation, although it's not always the best documentation out there.

    Here is the WebCamTexture documentation.

    Here is the WebCamDevice documentation.

    The Unity forums also contain a wealth of information and, depending on the problem, the Unity Engine Developers will sometimes answer questions.