Sample13_ToDoApp.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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.Linq;
  4. using UnityEngine;
  5. using UnityEngine.UI;
  6. using System.Collections;
  7. using UnityEngine.EventSystems;
  8. namespace UniRx.Examples
  9. {
  10. public class Sample13_ToDoApp : MonoBehaviour
  11. {
  12. // Open Sample13Scene. Set from canvas
  13. public Text Title;
  14. public InputField ToDoInput;
  15. public Button AddButton;
  16. public Button ClearButton;
  17. public GameObject TodoList;
  18. // prefab:)
  19. public GameObject SampleItemPrefab;
  20. ReactiveCollection<GameObject> toDos = new ReactiveCollection<GameObject>();
  21. void Start()
  22. {
  23. // merge Button click and push enter key on input field.
  24. var submit = Observable.Merge(
  25. AddButton.OnClickAsObservable().Select(_ => ToDoInput.text),
  26. ToDoInput.OnEndEditAsObservable().Where(_ => Input.GetKeyDown(KeyCode.Return)));
  27. // add to reactive collection
  28. submit.Where(x => x != "")
  29. .Subscribe(x =>
  30. {
  31. ToDoInput.text = ""; // clear input field
  32. var item = Instantiate(SampleItemPrefab) as GameObject;
  33. (item.GetComponentInChildren(typeof(Text)) as Text).text = x;
  34. toDos.Add(item);
  35. });
  36. // Collection Change Handling
  37. toDos.ObserveCountChanged().Subscribe(x => Title.text = "TODO App, ItemCount:" + x);
  38. toDos.ObserveAdd().Subscribe(x =>
  39. {
  40. x.Value.transform.SetParent(TodoList.transform, false);
  41. });
  42. toDos.ObserveRemove().Subscribe(x =>
  43. {
  44. GameObject.Destroy(x.Value);
  45. });
  46. // Clear
  47. ClearButton.OnClickAsObservable()
  48. .Subscribe(_ =>
  49. {
  50. var removeTargets = toDos.Where(x => x.GetComponent<Toggle>().isOn).ToArray();
  51. foreach (var item in removeTargets)
  52. {
  53. toDos.Remove(item);
  54. }
  55. });
  56. }
  57. }
  58. }
  59. #endif