WebBrowserInputChannelReceiver.cs 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. using System;
  2. using Unity.WebRTC;
  3. using UnityEngine;
  4. using UnityEngine.InputSystem;
  5. namespace Unity.RenderStreaming.Samples
  6. {
  7. /// <summary>
  8. ///
  9. /// </summary>
  10. [Serializable]
  11. class ButtonClickEvent : UnityEngine.Events.UnityEvent<int> { }
  12. /// <summary>
  13. ///
  14. /// </summary>
  15. [Serializable]
  16. class ButtonClickElement
  17. {
  18. [Tooltip("Specifies the ID on the HTML")]
  19. public int elementId;
  20. public ButtonClickEvent click;
  21. }
  22. /// <summary>
  23. ///
  24. /// </summary>
  25. public class WebBrowserInputChannelReceiver : InputChannelReceiverBase
  26. {
  27. /// <summary>
  28. ///
  29. /// </summary>
  30. [SerializeField, Tooltip("Array to set your own click event")]
  31. private ButtonClickElement[] arrayButtonClickEvent;
  32. /// <summary>
  33. ///
  34. /// </summary>
  35. public override event Action<InputDevice, InputDeviceChange> onDeviceChange;
  36. private RemoteInput remoteInput;
  37. /// <summary>
  38. ///
  39. /// </summary>
  40. /// <param name="track"></param>
  41. public override void SetChannel(string connectionId, RTCDataChannel channel)
  42. {
  43. if (channel == null)
  44. {
  45. if (remoteInput != null)
  46. {
  47. onDeviceChange?.Invoke(remoteInput.RemoteGamepad, InputDeviceChange.Removed);
  48. onDeviceChange?.Invoke(remoteInput.RemoteKeyboard, InputDeviceChange.Removed);
  49. onDeviceChange?.Invoke(remoteInput.RemoteMouse, InputDeviceChange.Removed);
  50. onDeviceChange?.Invoke(remoteInput.RemoteTouchscreen, InputDeviceChange.Removed);
  51. remoteInput.Dispose();
  52. remoteInput = null;
  53. }
  54. }
  55. else
  56. {
  57. remoteInput = RemoteInputReceiver.Create();
  58. remoteInput.ActionButtonClick = OnButtonClick;
  59. channel.OnMessage += remoteInput.ProcessInput;
  60. onDeviceChange?.Invoke(remoteInput.RemoteGamepad, InputDeviceChange.Added);
  61. onDeviceChange?.Invoke(remoteInput.RemoteKeyboard, InputDeviceChange.Added);
  62. onDeviceChange?.Invoke(remoteInput.RemoteMouse, InputDeviceChange.Added);
  63. onDeviceChange?.Invoke(remoteInput.RemoteTouchscreen, InputDeviceChange.Added);
  64. }
  65. base.SetChannel(connectionId, channel);
  66. }
  67. /// <summary>
  68. ///
  69. /// </summary>
  70. /// <param name="elementId"></param>
  71. public virtual void OnButtonClick(int elementId)
  72. {
  73. foreach (var element in arrayButtonClickEvent)
  74. {
  75. if (element.elementId == elementId)
  76. {
  77. element.click.Invoke(elementId);
  78. }
  79. }
  80. }
  81. /// <summary>
  82. ///
  83. /// </summary>
  84. public virtual void OnDestroy()
  85. {
  86. remoteInput?.Dispose();
  87. }
  88. }
  89. }