MaxEventExecutor.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. //
  2. // MaxEventExecutor.cs
  3. // Max Unity Plugin
  4. //
  5. // Created by Jonathan Liu on 1/22/2024.
  6. // Copyright © 2024 AppLovin. All rights reserved.
  7. //
  8. using System;
  9. using System.Collections.Generic;
  10. using UnityEngine;
  11. using UnityEngine.Events;
  12. namespace AppLovinMax.Internal
  13. {
  14. public class MaxEventExecutor : MonoBehaviour
  15. {
  16. private static MaxEventExecutor _instance;
  17. private static readonly List<MaxAction> AdEventsQueue = new List<MaxAction>();
  18. private static volatile bool _adEventsQueueEmpty = true;
  19. struct MaxAction
  20. {
  21. public readonly Action ActionToExecute;
  22. public readonly string EventName;
  23. public MaxAction(Action actionToExecute, string nameOfEvent)
  24. {
  25. ActionToExecute = actionToExecute;
  26. EventName = nameOfEvent;
  27. }
  28. }
  29. public static void InitializeIfNeeded()
  30. {
  31. if (_instance != null) return;
  32. var executor = new GameObject("MaxEventExecutor");
  33. executor.hideFlags = HideFlags.HideAndDontSave;
  34. DontDestroyOnLoad(executor);
  35. _instance = executor.AddComponent<MaxEventExecutor>();
  36. }
  37. #region Public API
  38. #if UNITY_EDITOR || !(UNITY_ANDROID || UNITY_IPHONE || UNITY_IOS)
  39. public static MaxEventExecutor Instance
  40. {
  41. get
  42. {
  43. InitializeIfNeeded();
  44. return _instance;
  45. }
  46. }
  47. #endif
  48. public static void ExecuteOnMainThread(Action action, string eventName)
  49. {
  50. lock (AdEventsQueue)
  51. {
  52. AdEventsQueue.Add(new MaxAction(action, eventName));
  53. _adEventsQueueEmpty = false;
  54. }
  55. }
  56. public static void InvokeOnMainThread(UnityEvent unityEvent, string eventName)
  57. {
  58. ExecuteOnMainThread(() => unityEvent.Invoke(), eventName);
  59. }
  60. #endregion
  61. public void Update()
  62. {
  63. if (_adEventsQueueEmpty) return;
  64. var actionsToExecute = new List<MaxAction>();
  65. lock (AdEventsQueue)
  66. {
  67. actionsToExecute.AddRange(AdEventsQueue);
  68. AdEventsQueue.Clear();
  69. _adEventsQueueEmpty = true;
  70. }
  71. foreach (var maxAction in actionsToExecute)
  72. {
  73. if (maxAction.ActionToExecute.Target != null)
  74. {
  75. try
  76. {
  77. maxAction.ActionToExecute.Invoke();
  78. }
  79. catch (Exception exception)
  80. {
  81. MaxSdkLogger.UserError("Caught exception in publisher event: " + maxAction.EventName + ", exception: " + exception);
  82. MaxSdkLogger.LogException(exception);
  83. }
  84. }
  85. }
  86. }
  87. public void Disable()
  88. {
  89. _instance = null;
  90. }
  91. }
  92. }