ServerTime.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using UnityEngine;
  2. using System.Collections;
  3. using System;
  4. public class ServerTime : MonoBehaviour
  5. {
  6. #region Unity Singleton
  7. private static ServerTime _instance;
  8. public static ServerTime Instance
  9. {
  10. get
  11. {
  12. if (_instance == null)
  13. {
  14. _instance = FindObjectOfType(typeof(ServerTime)) as ServerTime;
  15. if (_instance == null)
  16. {
  17. AVDebug.LogError(string.Format("No gameObject with {0} component exists. Make sure to create a gameObject with {0} component", new System.Diagnostics.StackFrame().GetMethod().DeclaringType));
  18. }
  19. }
  20. return _instance;
  21. }
  22. }
  23. void Awake()
  24. {
  25. if (_instance != null && _instance != this)
  26. {
  27. AVDebug.LogWarning(string.Format("{0} Instance already exists on another gameObject. Destroying this gameObject {1}", this.GetType().Name, gameObject.name));
  28. Destroy(gameObject);
  29. return;
  30. }
  31. _instance = this;
  32. DontDestroyOnLoad(gameObject);
  33. }
  34. #endregion
  35. /// <summary>
  36. /// Returns the server time as a Unix Time Stamp, i.e. current time in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT),
  37. /// through the onComplete action.
  38. /// If there was an error, -1 is returned through the onComplete action
  39. /// </summary>
  40. public void RetrieveServerTime(Action<long> onComplete)
  41. {
  42. AVDebug.Assert(onComplete != null, "onComplete must not be null when requesting server time");
  43. StartCoroutine(RetrieveServerTimeCoroutine(onComplete));
  44. }
  45. IEnumerator RetrieveServerTimeCoroutine(Action<long> onComplete)
  46. {
  47. WWW www = new WWW(GameConstants.SERVER_BASE_URL + "serverTime.php");
  48. yield return www;
  49. if (www.error != null)
  50. {
  51. onComplete(-1);
  52. } else
  53. {
  54. long serverTime;
  55. if (long.TryParse(www.text, out serverTime))
  56. {
  57. onComplete(serverTime);
  58. } else
  59. {
  60. onComplete(-1); //parse error
  61. }
  62. }
  63. }
  64. }