Sample04_ConvertFromUnityCallback.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using System;
  2. using UnityEngine;
  3. namespace UniRx.Examples
  4. {
  5. public class Sample04_ConvertFromUnityCallback : MonoBehaviour
  6. {
  7. // This is about log but more reliable log sample => Sample11_Logger
  8. private class LogCallback
  9. {
  10. public string Condition;
  11. public string StackTrace;
  12. public UnityEngine.LogType LogType;
  13. }
  14. static class LogHelper
  15. {
  16. // If static register callback, use Subject for event branching.
  17. #if (UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7)
  18. static Subject<LogCallback> subject;
  19. public static IObservable<LogCallback> LogCallbackAsObservable()
  20. {
  21. if (subject == null)
  22. {
  23. subject = new Subject<LogCallback>();
  24. // Publish to Subject in callback
  25. UnityEngine.Application.RegisterLogCallback((condition, stackTrace, type) =>
  26. {
  27. subject.OnNext(new LogCallback { Condition = condition, StackTrace = stackTrace, LogType = type });
  28. });
  29. }
  30. return subject.AsObservable();
  31. }
  32. #else
  33. // If standard evetns, you can use Observable.FromEvent.
  34. public static IObservable<LogCallback> LogCallbackAsObservable()
  35. {
  36. return Observable.FromEvent<Application.LogCallback, LogCallback>(
  37. h => (condition, stackTrace, type) => h(new LogCallback { Condition = condition, StackTrace = stackTrace, LogType = type }),
  38. h => Application.logMessageReceived += h, h => Application.logMessageReceived -= h);
  39. }
  40. #endif
  41. }
  42. void Awake()
  43. {
  44. // method is separatable and composable
  45. LogHelper.LogCallbackAsObservable()
  46. .Where(x => x.LogType == LogType.Warning)
  47. .Subscribe(x => Debug.Log(x));
  48. LogHelper.LogCallbackAsObservable()
  49. .Where(x => x.LogType == LogType.Error)
  50. .Subscribe(x => Debug.Log(x));
  51. }
  52. }
  53. }