Wednesday, 6 April 2016

Detecting Webcam in Unity3D using C#

This is a basic tutorial explains how to detect webcam in Unity3D.


  • Create a new project in Unity3D
  • Create a new plane in unity3D under GameObject >> 3D Object >> Plane
  • Set the Y rotation of plane to 180.
  • Create a new folder named "Scripts" under assets.
  • Create a new C# file under the Scripts folder and name it as DetectWebcam
  • Drag the script over plane / Attach the script on the newly created plane

  • Double click the DetectWebcam script file to launch Monodevelop/ Visual studio.
  • Copy & paste the below code.

using UnityEngine;
using System.Collections;
public class DetectWebcam : MonoBehaviour
{
    void Start() 
    {
        WebCamDevice[] devices = WebCamTexture.devices;
        for( var i = 0 ; i < devices.Length ; i++ )
        {
            Debug.Log(devices[i].name);// Gets the list of available devices and prints its name
        }

        string deviceName = WebCamTexture.devices[0].name;
        WebCamTexture newTexture = new WebCamTexture(deviceName, 640, 360, 30);
        newTexture.Play();

        gameObject.GetComponent<Renderer>().material.mainTexture = newTexture;
            
    }
}
  • Save the code and play the scene in Unity3D.
  • That's it 

No comments:

Post a Comment