摄像头画面显示于unity场景


🐾 个人主页 🐾

🪧阿松爱睡觉,横竖醒不来 🏅你可以不屠龙,但不能不磨剑🗡


目录

一、前言

由于标题限制,这篇文章主要是讲在unity中调用摄像头,然后将摄像头捕捉到的画面显示到场景中,无论是UI画面还是场景中的某个物体上;至于应用的场景可以用于AR增强现实。

那么话不多说,直接开始今天的内容吧!

二、UI画面

  1. 首先创建一个RawImage,用于在UI中显示画面
  2. 调整RawImage尺寸,不调整也行,这里调整主要便于演示。
    选中RawImage,然后点击Rect Transform中的方标,然后按住Alt键的同时点击最右下角的位置,直至RawImage铺满屏幕。
  3. 创建一个脚本文件,并键入以下的代码
csharp 复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class WebCamToUI : MonoBehaviour
{
    // 显示视频画面的RawImage
    public RawImage rawImage; 

    // Start is called before the first frame update
    void Start()
    {
        // 创建一个WebCamTexture实例
        WebCamTexture webcamTexture = new WebCamTexture();

        // 将WebCamTexture应用到RawImage上
        rawImage.texture = webcamTexture;

        // 开始播放摄像头的纹理
        webcamTexture.Play();
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}
  1. 将脚本挂载到RawImage中,然后将开始创建的RawImage赋值给变量rawImage
  2. 运行看效果

    不好意思,搞错了,重来。

三、显示于场景

在场景中显示和在UI中显示的逻辑其实大差不差,还是比较相似的,这里以Cube为例,也可以用QuadPlane

  1. 创建一个Cube
  2. 创建一个脚本文件,键入以下代码
csharp 复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class WebCamToScene : MonoBehaviour
{
	// 需要显示摄像头内容的物体的MeshRenderer组件
    public MeshRenderer meshRenderer; 

    // Start is called before the first frame update
    void Start()
    {
        // 创建WebCamTexture实例
        WebCamTexture webcamTexture = new WebCamTexture();

        // 创建一个材质并应用摄像头纹理
        Material material = new Material(Shader.Find("Unlit/Texture"));
        material.mainTexture = webcamTexture;

        // 将材质应用到MeshRenderer上
        meshRenderer.material = material;

        // 开始播放摄像头纹理
        webcamTexture.Play();
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}
  1. 挂载脚本,赋值变量。
    这里直接拖物体只由于创建的物体中自带有Mesh Renderer组件
  2. 运行看效果

    其他的物体也可以,比如前面提到的QuadPlane

四、结语

文章看完后别忘了自己不看步骤再做一遍,巩固一下,记住脚本中的API。

这一期文章的内容就到这里,下期见,拜拜。

相关推荐
阿Q说代码1 小时前
开篇:从理论到实践,体验openEuler嵌入式开发全流程
unity·游戏引擎
zxb@hny2 小时前
Hazel游戏引擎学习
学习·游戏引擎
周小码4 小时前
Godot:10万星开源游戏引擎的硬核解析
游戏引擎·godot
qq_2052790515 小时前
Unity log工具 Unity Logviewer插件
unity·游戏引擎
IMPYLH16 小时前
Lua 的 tonumber 函数
开发语言·笔记·后端·junit·游戏引擎·lua
tealcwu17 小时前
【Unity实战】如何使用VS Code在真实iOS设备上调试 Unity应用
unity·游戏引擎·iphone
冰凌糕1 天前
Unity3D Shader 顶点和片段着色器
unity
Echo_NGC22371 天前
【AirSim 教程指南】Part 3:相机与传感器(RGB / 深度 / 分割 / LiDAR)
人工智能·计算机视觉·游戏引擎·ar·无人机·图形渲染·着色器
tealcwu1 天前
【Unity实战】如何使用VS Code在真实Android设备上调试 Unity应用
android·unity·游戏引擎
IMPYLH1 天前
Lua 的 setmetatable 函数
开发语言·笔记·后端·游戏引擎·lua