本文讲的这个程序是非常基础的。主要功能是同时打开手机前后摄像头,并且显示在屏幕上。在做这个实验之前,需要先配置Unity3D的安卓开发环境,这需要下载JDK和安卓SDK,具体的步骤请参照网上的教程。本文假设你已经配置好了环境。
在Unity的场景中生成如图所示的两个平板,一大一小,作为图像的载体。需要有一个摄像机来拍摄这两块板子,用于呈现最终的画面。我使用的是正交摄像机,这样比较好调整位置。当然是用透视摄像机也是可以的。然后将下面的ReadCamera.cs脚本绑定到MainCamera上。其中有几个公有变量需要设置一下。Plane1和Plane2分别绑定前后两个板子。GuiSkin需要自己先生成一个,然后设置好相关参数,再绑定到GuiSkin上。
发布一个APK文件,安装到手机上,即可观看到结果。
using UnityEngine;
using System.Collections;
public class ReadCamera : MonoBehaviour {
public string deviceName1;
WebCamTexture tex1;//接收返回的图片数据
public string deviceName2;
WebCamTexture tex2;//接收返回的图片数据
public GameObject plane1;
public GameObject plane2;
bool turn = true;
public GUISkin guiSkin;
void Start () {
StartCoroutine(test1());
StartCoroutine(test2());
}
// Update is called once per frame
void Update () {
plane1.GetComponent<Renderer>().material.mainTexture = turn?tex1:tex2;
plane2.GetComponent<Renderer>().material.mainTexture = turn?tex2:tex1;
}
void OnGUI()
{
GUI.skin = guiSkin;
if (GUI.Button(new Rect(20, 20, 300, 100), "翻转"))
{
turn = !turn;
}
}
IEnumerator test1()
{
yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);//授权
if (Application.HasUserAuthorization(UserAuthorization.WebCam))
{
WebCamDevice[] devices = WebCamTexture.devices;
deviceName1 = devices[0].name;
//设置摄像机摄像的区域
tex1 = new WebCamTexture(deviceName1, 1280, 720, 30);
tex1.Play();//开始摄像
}
}
IEnumerator test2()
{
yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);//授权
if (Application.HasUserAuthorization(UserAuthorization.WebCam))
{
WebCamDevice[] devices = WebCamTexture.devices;
deviceName2 = devices[1].name;
//设置摄像机摄像的区域
tex2 = new WebCamTexture(deviceName2, 640, 480, 30);
tex2.Play();//开始摄像
}
}
}