如何在Unity中获取物理设备摄像头的真实百万像素(MP)分辨率
问题核心原因
- 原代码计算的是宽高比(
w/h),不是总像素值,无法输出MP格式结果 - 调用
WebCamTexture.Play()后摄像头需要初始化时间,立刻读取宽高大概率拿到16x16的默认初始值,结果错误 - 缺失总像素转百万像素(MP)的单位换算逻辑
修复步骤
首先在脚本类中声明成员变量:
private WebCamTexture backCam;
修改后的协程代码如下:
IEnumerator CameraResolution() { WebCamDevice[] devices = WebCamTexture.devices; Debug.Log("Number of web cams connected: " + devices.Length); for (int i = 0; i < devices.Length; i++) { string camName = devices[i].name; Debug.Log("selected webcam name is " + camName); if (backCam == null) backCam = new WebCamTexture(); backCam.deviceName = camName; GetComponent<Renderer>().material.mainTexture = backCam; if (!backCam.isPlaying) backCam.Play(); // 等待摄像头初始化完成,避免读取到默认值 yield return new WaitUntil(() => backCam.width > 16 && backCam.height > 16); float h = backCam.height; float w = backCam.width; // 总像素换算为百万像素单位,保留1位小数输出 float megaPixel = (w * h) / 1000000f; Debug.Log($"The camera pixel is: {megaPixel:F1}MP"); backCam.Stop(); yield return null; } }
关键修改说明
- 新增初始化等待逻辑,确保读取到摄像头真实的宽高参数
- 将宽高比计算改为总像素计算,增加单位换算逻辑,输出格式符合需求
- 调整摄像头停止时机,避免参数未读取就停止运行的问题
注意事项
- 移动端运行需要提前在Player Settings中开启摄像头权限,否则无法检测到摄像设备
- 如果需要获取设备支持的最高分辨率,可在初始化
WebCamTexture时传入预期的最大宽高,系统会自动匹配最接近的可用分辨率,示例:new WebCamTexture(7680, 4320)
内容的提问来源于stack exchange,提问作者sekmani med amine
相关产品推荐
相关产品推荐

