AR中会用到设备的摄像头,那么又如何去在Unity3D中去调用摄像头呢?
原地址:http://blog.csdn.net/wuyt2008/article/details/50684236
如下代码:
-
using UnityEngine;
-
using System.Collections;
-
-
public class WebCamManager : MonoBehaviour {
-
-
// Use this for initialization
-
void Start () {
-
-
WebCamTexture webcamTexture = new WebCamTexture ();
-
-
//如果有后置摄像头,调用后置摄像头
-
for (int i = 0; i < WebCamTexture.devices.Length; i++) {
-
if (!WebCamTexture.devices [i].isFrontFacing) {
-
webcamTexture.deviceName = WebCamTexture.devices [i].name;
-
break;
-
}
-
}
-
-
Renderer renderer = GetComponent<Renderer>();
-
renderer.material.mainTexture = webcamTexture;
-
webcamTexture.Play();
-
}
-
-
}
在场景里面添加一个plane

调整plane的位置,并把脚本拖上去,运行就可以了。

如果是要在GUITexture上显示,则代码如下:
-
using UnityEngine;
-
using System.Collections;
-
-
public class WebCamManager : MonoBehaviour {
-
-
// Use this for initialization
-
void Start () {
-
-
WebCamTexture webcamTexture = new WebCamTexture ();
-
-
//如果有后置摄像头,调用后置摄像头
-
for (int i = 0; i < WebCamTexture.devices.Length; i++) {
-
if (!WebCamTexture.devices [i].isFrontFacing) {
-
webcamTexture.deviceName = WebCamTexture.devices [i].name;
-
break;
-
}
-
}
-
-
GUITexture guiTexture = GetComponent<GUITexture> ();
-
guiTexture.texture = webcamTexture;
-
webcamTexture.Play ();
-
}
-
}
如果在本机调试的时候出现以下错误提示
-
Cannot use web cam, since the user has not authorized this!
这是没有使用摄像头的权限,build一次安卓应用再试就好了,或者使用以下代码,先判断权限
-
using UnityEngine;
-
using System.Collections;
-
-
public class WebcamManager : MonoBehaviour {
-
-
// Use this for initialization
-
void Start () {
-
StartCoroutine ("CallWebCam");
-
}
-
-
IEnumerator CallWebCam(){
-
yield return Application.RequestUserAuthorization (UserAuthorization.WebCam);
-
-
if (Application.HasUserAuthorization (UserAuthorization.WebCam)) {
-
WebCamTexture webcamTexture = new WebCamTexture ();
-
-
//如果有后置摄像头,调用后置摄像头
-
for (int i = 0; i < WebCamTexture.devices.Length; i++) {
-
if (!WebCamTexture.devices [i].isFrontFacing) {
-
webcamTexture.deviceName = WebCamTexture.devices [i].name;
-
break;
-
}
-
}
-
-
GUITexture guiTexture = GetComponent<GUITexture> ();
-
guiTexture.texture = webcamTexture;
-
webcamTexture.Play ();
-
} else {
-
Debug.Log ("has not authorization");
-
}
-
}
-
}