neuecc / UniRx

Reactive Extensions for Unity
MIT License
7.01k stars 895 forks source link

Detect webcam connect/disconnect #450

Open ReallyRad opened 4 years ago

ReallyRad commented 4 years ago

Hello, I am trying to get started with UniRx. My use case is trying to detect a webcam being connected/disconnected from my PC.

For the moment, I am looking at the number of devices connected in WebCamTexture.devices.

ReactiveCollection<WebCamTexture> myCollection; myCollection = new ReactiveCollection<WebCamTexture>(); WebCamTexture.devices.ToReactiveCollection(); myCollection.ObserveCountChanged().Subscribe(_ => Debug.Log("count changed"));

which doesn't seem to trigger at all. Any pointers on how to do that would be much appreciated. thank you

FodderMK commented 4 years ago

ToReactiveCollection() makes a copy of the data, it is not continually updating that list of devices. There's no hook between the devices and your collection to signal any update is needed.

I don't see any kind of event that Unity fires when that value changes so I'd probably check it on an interval.

// Checks the devices every 5 seconds
var currentCount = WebCamTexture.devices.Length;
Observable.Interval(TimeSpan.FromSeconds(5))
  .Select(_ => WebCamTexture.devices)
  .Where(devices => devices.Length != currentCount)
  .Subscribe(devices => {
    currentCount = devices.Length;
    Debug.Log("count changed");
  });
ReallyRad commented 4 years ago

Makes perfect sense, thanks!