InputValue.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. using System;
  2. using System.Diagnostics;
  3. using UnityEngine.InputSystem.Controls;
  4. ////TODO: API to get the control and device from the internal context
  5. ////TODO: ToString()
  6. namespace UnityEngine.InputSystem
  7. {
  8. /// <summary>
  9. /// Wraps around values provided by input actions.
  10. /// </summary>
  11. /// <remarks>
  12. /// This is a wrapper around <see cref="InputAction.CallbackContext"/> chiefly for use
  13. /// with GameObject messages (i.e. <see cref="GameObject.SendMessage(string,object)"/>). It exists
  14. /// so that action callback data can be represented as an object, can be reused, and shields
  15. /// the receiver from having to know about action callback specifics.
  16. /// </remarks>
  17. /// <seealso cref="InputAction"/>
  18. [DebuggerDisplay("Value = {Get()}")]
  19. public class InputValue
  20. {
  21. /// <summary>
  22. /// Read the value as an object.
  23. /// </summary>
  24. /// <remarks>
  25. /// This method allocates GC memory and will thus created garbage. If used during gameplay,
  26. /// it will lead to GC spikes.
  27. /// </remarks>
  28. /// <returns>The current value in the form of a boxed object.</returns>
  29. public object Get()
  30. {
  31. return m_Context.Value.ReadValueAsObject();
  32. }
  33. ////TODO: add automatic conversions
  34. public TValue Get<TValue>()
  35. where TValue : struct
  36. {
  37. if (!m_Context.HasValue)
  38. throw new InvalidOperationException($"Values can only be retrieved while in message callbacks");
  39. return m_Context.Value.ReadValue<TValue>();
  40. }
  41. ////TODO: proper message if value type isn't right
  42. public bool isPressed => Get<float>() >= ButtonControl.s_GlobalDefaultButtonPressPoint;
  43. internal InputAction.CallbackContext? m_Context;
  44. }
  45. }