本文共 2458 字,大约阅读时间需要 8 分钟。
要通过Unity3D实现原生WebCamera调用外部摄像头显示,可以按照以下步骤操作:
在Unity3D项目中,您需要以下组件:
在场景中:
Resources 文件夹,并在其下创建 Material 文件夹。Material 文件夹中新建 CameraPlane.mat 材质文件,并设置其Shader为 Unlit/Texture。在场景中创建一个 Camera 组件,将其重命名为 WebCamera。在 WebCamera 节点下创建一个子对象 Plane,并设置其 Plane 子 Yield:
Rotation (X: 90, Y: 180, Z: 0),以避免画面反转问题。CameraPlane.mat 材质球附加到 Plane 的 MeshRenderer 上。在 WebCamera 节点上附加 WebCameraManager.cs 组件,用于处理外部摄像头的调用及显示:
using System.Collections;using System.Collections.Generic;using UnityEngine;public class WebCameraManager : MonoBehaviour{    public string DeviceName;    public Vector2 CameraSize;    public float CameraFPS;    public WebCamTexture _webCamera;    public GameObject Plane;    void OnGUI()    {        if (GUI.Button(new Rect(100, 100, 100, 100), "Initialize Camera"))        {            StartCoroutine("InitCameraCor");        }        if (GUI.Button(new Rect(100, 250, 100, 100), "ON/OFF"))        {            if (_webCamera != null && Plane != null)            {                if (_webCamera.isPlaying)                    StopCamera();                else                    PlayCamera();            }        }        if (GUI.Button(new Rect(100, 450, 100, 100), "Quit"))        {            Application.Quit();        }    }    public void PlayCamera()    {        Plane.GetComponent       ().enabled = true;        _webCamera.Play();    }    public void StopCamera()    {        Plane.GetComponent         ().enabled = false;        _webCamera.Stop();    }    public IEnumerator InitCameraCor()    {        yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);        if (Application.HasUserAuthorization(UserAuthorization.WebCam))        {            WebCamDevice[] devices = WebCamTexture.devices;            DeviceName = devices[0].name;            _webCamera = new WebCamTexture(DeviceName, (int)CameraSize.x, (int)CameraSize.y, (int)CameraFPS);            Plane.GetComponent           ().material.mainTexture = _webCamera;            Plane.transform.localScale = new Vector3(1, 1, 1);            _webCamera.Play();        }    }}                 完成以上设置后,运行项目并查看效果。通过添加摄像头面板和控制按钮,您可以实时查看外部摄像头的图像。ON/OFF 按钮可控制摄像头的播放和暂停,其余操作可以通过脚本控制自动化。
通过以上步骤,您可以轻松实现Unity3D原生WebCamera调用外部摄像头,并直观显示摄像头画面。这一实现既简洁又高效,适用于多种摄像头设备和场景需求。
转载地址:http://cztxz.baihongyu.com/