123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172 |
- using UnityEngine;
- using System.Collections;
- using System;
- public class ServerTime : MonoBehaviour
- {
- #region Unity Singleton
- private static ServerTime _instance;
- public static ServerTime Instance
- {
- get
- {
- if (_instance == null)
- {
- _instance = FindObjectOfType(typeof(ServerTime)) as ServerTime;
- if (_instance == null)
- {
- 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));
- }
- }
- return _instance;
- }
- }
- void Awake()
- {
- if (_instance != null && _instance != this)
- {
- AVDebug.LogWarning(string.Format("{0} Instance already exists on another gameObject. Destroying this gameObject {1}", this.GetType().Name, gameObject.name));
- Destroy(gameObject);
- return;
- }
- _instance = this;
- DontDestroyOnLoad(gameObject);
- }
- #endregion
- /// <summary>
- /// 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),
- /// through the onComplete action.
- /// If there was an error, -1 is returned through the onComplete action
- /// </summary>
- public void RetrieveServerTime(Action<long> onComplete)
- {
- AVDebug.Assert(onComplete != null, "onComplete must not be null when requesting server time");
- StartCoroutine(RetrieveServerTimeCoroutine(onComplete));
- }
- IEnumerator RetrieveServerTimeCoroutine(Action<long> onComplete)
- {
- WWW www = new WWW(GameConstants.SERVER_BASE_URL + "serverTime.php");
- yield return www;
- if (www.error != null)
- {
- onComplete(-1);
- } else
- {
- long serverTime;
- if (long.TryParse(www.text, out serverTime))
- {
- onComplete(serverTime);
- } else
- {
- onComplete(-1); //parse error
- }
- }
- }
- }
|