Analytics.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using Sirenix.OdinInspector;
  5. using mixpanel;
  6. namespace KairoEngine.Analytics
  7. {
  8. /// <summary>Send analytics events to Mixpanel</summary>
  9. [HideMonoScript] public class Analytics : MonoBehaviour
  10. {
  11. public static Analytics instance;
  12. public bool trackEvents = true;
  13. public bool debugEvents = true;
  14. public bool clearEventsOnStart = false;
  15. void OnApplicationQuit() => Mixpanel.Disable();
  16. void Awake()
  17. {
  18. if(instance == null) instance = this;
  19. else Destroy(this);
  20. if(clearEventsOnStart) Mixpanel.ClearTimedEvents();
  21. Mixpanel.Init();
  22. }
  23. public static bool IsTracking() => instance != null ? instance.trackEvents : false;
  24. public static bool ShowDebug() => instance != null ? instance.debugEvents : false;
  25. public static void Identify(string playerID) => Mixpanel.Identify(playerID);
  26. public static void Register(string propertieTitle, int propertyValue) => Mixpanel.Register(propertieTitle, propertyValue);
  27. public static void Register(string propertieTitle, float propertyValue) => Mixpanel.Register(propertieTitle, propertyValue);
  28. public static void Register(string propertieTitle, string propertyValue) => Mixpanel.Register(propertieTitle, propertyValue);
  29. public static void StartTimedEvent(string title) => Mixpanel.StartTimedEvent(title);
  30. public static void Flush() => Mixpanel.Flush();
  31. public static void Track(string eventTitle)
  32. {
  33. if(IsTracking()) Mixpanel.Track(eventTitle);
  34. if(ShowDebug()) Debug.Log($"Tracking event \'{eventTitle}\'");
  35. }
  36. public static void Track(string eventTitle, Value props)
  37. {
  38. if(IsTracking()) Mixpanel.Track(eventTitle, props);
  39. if(ShowDebug()) Debug.Log($"Tracking event \'{eventTitle}\', {props.ToString()}");
  40. }
  41. public static void Track(string eventTitle, Dictionary<string, System.Object> dictionary)
  42. {
  43. if(!IsTracking()) return;
  44. var props = new Value();
  45. foreach (var item in dictionary)
  46. {
  47. if(item.Value.GetType() == typeof(int)) props[item.Key] = (int)item.Value;
  48. else if(item.Value.GetType() == typeof(string)) props[item.Key] = (string)item.Value;
  49. else if(item.Value.GetType() == typeof(float)) props[item.Key] = (float)item.Value;
  50. }
  51. Mixpanel.Track(eventTitle, props);
  52. if(ShowDebug()) Debug.Log($"Tracking event \'{eventTitle}\', {props.ToString()}");
  53. }
  54. }
  55. }