Advertisement
NilsKirchhoff

WebcamAverageColor

Jul 19th, 2025 (edited)
318
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.48 KB | None | 0 0
  1. using System;
  2. using System.Collections;
  3. using UnityEngine;
  4. using UnityEngine.Rendering;
  5.  
  6. public class CaptureDevice : MonoBehaviour
  7. {
  8.     [SerializeField] WebCamDevice[] devices;
  9.     WebCamTexture webcamTexture;
  10.     new Renderer renderer;
  11.  
  12.     [SerializeField] Light screenLight;
  13.  
  14.     RenderTexture _rendTex;
  15.     void Start()
  16.     {
  17.         devices = WebCamTexture.devices;
  18.         for (int i = 0; i < devices.Length; i++)
  19.             Debug.Log(devices[i].name);
  20.  
  21.         InitializeCamera();
  22.     }
  23.  
  24.     private void InitializeCamera()
  25.     {
  26.         webcamTexture = new WebCamTexture();
  27.         renderer = GetComponent<Renderer>();
  28.        
  29.         if (devices.Length > 0)
  30.         {
  31.             webcamTexture.deviceName = devices[0].name;
  32.             renderer.material.mainTexture = webcamTexture;
  33.             webcamTexture.Play();
  34.  
  35.             _rendTex = new RenderTexture(webcamTexture.width, webcamTexture.height, 0);
  36.             _rendTex.useMipMap = true;
  37.             _rendTex.autoGenerateMips = true;
  38.         }
  39.     }
  40.  
  41.     private void FixedUpdate()
  42.     {
  43.         GetAveragebyMipmap();
  44.     }
  45.  
  46.     private void GetAveragebyMipmap()
  47.     {
  48.         Graphics.Blit(webcamTexture, _rendTex);
  49.  
  50.         var asyncAction = AsyncGPUReadback.Request(_rendTex, _rendTex.mipmapCount - 1);
  51.         asyncAction.WaitForCompletion();
  52.  
  53.         // Extract average color
  54.         Color32 Average = asyncAction.GetData<Color32>()[0];
  55.         screenLight.color = Average;
  56.     }
  57. }
  58.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement