NearbyHelperObject.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. #if UNITY_ANDROID
  2. namespace GooglePlayGames.OurUtils
  3. {
  4. using BasicApi.Nearby;
  5. using System;
  6. using UnityEngine;
  7. public class NearbyHelperObject : MonoBehaviour
  8. {
  9. // our (singleton) instance
  10. private static NearbyHelperObject instance = null;
  11. // timers to keep track of discovery and advertising
  12. private static double mAdvertisingRemaining = 0;
  13. private static double mDiscoveryRemaining = 0;
  14. // nearby client to stop discovery and to stop advertising
  15. private static INearbyConnectionClient mClient = null;
  16. public static void CreateObject(INearbyConnectionClient client)
  17. {
  18. if (instance != null)
  19. {
  20. return;
  21. }
  22. mClient = client;
  23. if (Application.isPlaying)
  24. {
  25. // add an invisible game object to the scene
  26. GameObject obj = new GameObject("PlayGames_NearbyHelper");
  27. DontDestroyOnLoad(obj);
  28. instance = obj.AddComponent<NearbyHelperObject>();
  29. }
  30. else
  31. {
  32. instance = new NearbyHelperObject();
  33. }
  34. }
  35. private static double ToSeconds(TimeSpan? span)
  36. {
  37. if (!span.HasValue)
  38. {
  39. return 0;
  40. }
  41. if (span.Value.TotalSeconds < 0)
  42. {
  43. return 0;
  44. }
  45. return span.Value.TotalSeconds;
  46. }
  47. public static void StartAdvertisingTimer(TimeSpan? span)
  48. {
  49. mAdvertisingRemaining = ToSeconds(span);
  50. }
  51. public static void StartDiscoveryTimer(TimeSpan? span)
  52. {
  53. mDiscoveryRemaining = ToSeconds(span);
  54. }
  55. public void Awake()
  56. {
  57. DontDestroyOnLoad(gameObject);
  58. }
  59. public void OnDisable()
  60. {
  61. if (instance == this)
  62. {
  63. instance = null;
  64. }
  65. }
  66. public void Update()
  67. {
  68. // check if currently advertising
  69. if (mAdvertisingRemaining > 0)
  70. {
  71. mAdvertisingRemaining -= Time.deltaTime;
  72. if (mAdvertisingRemaining < 0)
  73. {
  74. mClient.StopAdvertising();
  75. }
  76. }
  77. // check if currently discovering
  78. if (mDiscoveryRemaining > 0)
  79. {
  80. mDiscoveryRemaining -= Time.deltaTime;
  81. if (mDiscoveryRemaining < 0)
  82. {
  83. mClient.StopDiscovery(mClient.GetServiceId());
  84. }
  85. }
  86. }
  87. }
  88. }
  89. #endif