Sample12_ReactiveProperty.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // for uGUI(from 4.6)
  2. #if !(UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5)
  3. using System;
  4. using UnityEngine;
  5. using UnityEngine.UI;
  6. namespace UniRx.Examples
  7. {
  8. public class Sample12_ReactiveProperty : MonoBehaviour
  9. {
  10. // Open Sample12Scene. Set from canvas
  11. public Button MyButton;
  12. public Toggle MyToggle;
  13. public InputField MyInput;
  14. public Text MyText;
  15. public Slider MySlider;
  16. // You can monitor/modifie in inspector by SpecializedReactiveProperty
  17. public IntReactiveProperty IntRxProp = new IntReactiveProperty();
  18. Enemy enemy = new Enemy(1000);
  19. void Start()
  20. {
  21. // UnityEvent as Observable
  22. // (shortcut, MyButton.OnClickAsObservable())
  23. MyButton.onClick.AsObservable().Subscribe(_ => enemy.CurrentHp.Value -= 99);
  24. // Toggle, Input etc as Observable(OnValueChangedAsObservable is helper for provide isOn value on subscribe)
  25. // SubscribeToInteractable is UniRx.UI Extension Method, same as .interactable = x)
  26. MyToggle.OnValueChangedAsObservable().SubscribeToInteractable(MyButton);
  27. // input shows delay after 1 second
  28. #if !(UNITY_4_6 || UNITY_4_7 || UNITY_5_0 || UNITY_5_1 || UNITY_5_2)
  29. MyInput.OnValueChangedAsObservable()
  30. #else
  31. MyInput.OnValueChangeAsObservable()
  32. #endif
  33. .Where(x => x != null)
  34. .Delay(TimeSpan.FromSeconds(1))
  35. .SubscribeToText(MyText); // SubscribeToText is UniRx.UI Extension Method
  36. // converting for human visibility
  37. MySlider.OnValueChangedAsObservable()
  38. .SubscribeToText(MyText, x => Math.Round(x, 2).ToString());
  39. // from RxProp, CurrentHp changing(Button Click) is observable
  40. enemy.CurrentHp.SubscribeToText(MyText);
  41. enemy.IsDead.Where(isDead => isDead == true)
  42. .Subscribe(_ =>
  43. {
  44. MyToggle.interactable = MyButton.interactable = false;
  45. });
  46. // initial text:)
  47. IntRxProp.SubscribeToText(MyText);
  48. }
  49. }
  50. // Reactive Notification Model
  51. public class Enemy
  52. {
  53. public IReactiveProperty<long> CurrentHp { get; private set; }
  54. public IReadOnlyReactiveProperty<bool> IsDead { get; private set; }
  55. public Enemy(int initialHp)
  56. {
  57. // Declarative Property
  58. CurrentHp = new ReactiveProperty<long>(initialHp);
  59. IsDead = CurrentHp.Select(x => x <= 0).ToReactiveProperty();
  60. }
  61. }
  62. }
  63. #endif