NilsKirchhoff icon

WebcamAverageColor

NilsKirchhoff | PRO | 07/19/25 05:28:42 AM UTC (Edited) | 0 ⭐ | 13587 👁️ | Never ⏰ | []
C# |

1.48 KB

|

None

|

0 👍

/

0 👎

using System;
using System.Collections;
using UnityEngine;
using UnityEngine.Rendering;
 
public class CaptureDevice : MonoBehaviour
{
    [SerializeField] WebCamDevice[] devices;
    WebCamTexture webcamTexture;
    new Renderer renderer;
 
    [SerializeField] Light screenLight;
 
    RenderTexture _rendTex;
    void Start()
    {
        devices = WebCamTexture.devices;
        for (int i = 0; i < devices.Length; i++)
            Debug.Log(devices[i].name);
 
        InitializeCamera();
    }
 
    private void InitializeCamera()
    {
        webcamTexture = new WebCamTexture();
        renderer = GetComponent<Renderer>();
        
        if (devices.Length > 0)
        {
            webcamTexture.deviceName = devices[0].name;
            renderer.material.mainTexture = webcamTexture;
            webcamTexture.Play();
 
            _rendTex = new RenderTexture(webcamTexture.width, webcamTexture.height, 0);
            _rendTex.useMipMap = true;
            _rendTex.autoGenerateMips = true;
        }
    }
 
    private void FixedUpdate()
    {
        GetAveragebyMipmap();
    }
 
    private void GetAveragebyMipmap()
    {
        Graphics.Blit(webcamTexture, _rendTex);
 
        var asyncAction = AsyncGPUReadback.Request(_rendTex, _rendTex.mipmapCount - 1);
        asyncAction.WaitForCompletion();
 
        // Extract average color
        Color32 Average = asyncAction.GetData<Color32>()[0];
        screenLight.color = Average;
    }
}
 

Comments

  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎

    
        
  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎