您的位置:首页 > 移动开发 > Unity3D

Unity3d,调用摄像头显示

2016-02-18 10:17 555 查看
先上代码

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");
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: