在场景中添加RawImage组件。
在其父节点上挂载CallCamera脚本。CallCamera脚本如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class CallCamera : MonoBehaviour
{
[HideInInspector]
public WebCamTexture webTex;
[HideInInspector]
public string deviceName;
//现实摄像头画面
public RawImage rawImage;
void Awake()
{
StartCoroutine(IECallCamera());
}
IEnumerator IECallCamera()
{
yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);
if (Application.HasUserAuthorization(UserAuthorization.WebCam))
{
WebCamDevice[] devices = WebCamTexture.devices;
如果有前置摄像头,调用前置摄像头
//for (int i = 0; i < devices.Length; i++)
//{
// if (devices[i].isFrontFacing)
// {
// deviceName = devices[i].name;
// break;
// }
//}
//如果有后置摄像头,调用后置摄像头
for (int i = 0; i < devices.Length; i++)
{
if (!devices[i].isFrontFacing)
{
deviceName = devices[i].name;
break;
}
}
//设置摄像机摄像的区域
webTex = new WebCamTexture(deviceName, Screen.width, Screen.height, 20);
webTex.Play();//开始摄像
#if UNITY_ANDROID
float physicscreen = Mathf.Sqrt(Screen.width * Screen.width + Screen.height * Screen.height) / Screen.dpi;
if (physicscreen >= 7f)
{
Debug.Log("安卓平板");
}
else
{
Debug.Log("安卓手机");
}
#elif UNITY_IPHONE
Debug.Log(UnityEngine.iOS.Device.generation);
string iP_genneration = UnityEngine.iOS.Device.generation.ToString();
//The second Mothod:
//string iP_genneration=SystemInfo.deviceModel.ToString();
Debug.Log(iP_genneration);
if (iP_genneration.Substring(0, 3) == "iPa")
{
Debug.Log("苹果平板");
rawImage.GetComponent<RectTransform>().sizeDelta = new Vector2(Screen.height , Screen.width);
}
else
{
Debug.Log("苹果手机");
rawImage.GetComponent<RectTransform>().sizeDelta = new Vector2(Screen.height, Screen.width );
}
#endif
rawImage.texture = webTex;
}
}
private void OnEnable()
{
Debug.Log("OnEnable");
if (webTex != null)
{
webTex.Play();//开始摄像
}
}
public void OnDisable()
{
Debug.Log("OnDisable");
webTex.Stop();
}
}
绑定RawImage在脚本上。
运行游戏,摄像机内容即可显示在RawImage上。
原文链接:https://blog.csdn.net/weixin_41573444/article/details/115578878