使用WebCamTexture把相机的画面显示到 RawImage 上
using UnityEngine;
using UnityEngine.UI;
public class WebCamTextureTest : MonoBehaviour
{
public RawImage RawImage;
private WebCamTexture _webCamTexture;
private Color32[] _colorBuff;
private Texture2D _texture2D;
void Start()
{
WebCamDevice[] devices = WebCamTexture.devices;
int length = devices.Length;
if (length > 0)
{
_webCamTexture = new WebCamTexture();
}
_webCamTexture.Play();
}
void Update()
{
if (_webCamTexture != null && _webCamTexture.isPlaying && _webCamTexture.didUpdateThisFrame)
{
int width = _webCamTexture.width;
int height = _webCamTexture.height;
if (_colorBuff == null)
{
_colorBuff = new Color32[width * height];
}
_webCamTexture.GetPixels32(_colorBuff);
if (_texture2D == null)
{
_texture2D = new Texture2D(width, height, TextureFormat.RGBA32, false);
}
_texture2D.SetPixels32(_colorBuff);
_texture2D.Apply();
RawImage.texture = _texture2D;
}
}
}
执行 WebCamTexture.Play() 报下面的错误
Could not start graph
Could not pause pControl
这两个错是因为摄像头被占用,需要检查代码中其他调用摄像头的地方