Created
September 26, 2017 12:35
-
-
Save Reyth3/459a4f9d518346bf95a5183c2a5b16d7 to your computer and use it in GitHub Desktop.
Time Passage Handling in Unity3D
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
public class TimeManipulation : MonoBehaviour { | |
#region Fields and Events | |
private static TimeManipulation _current; | |
private DateTime lastCheck; | |
public delegate void TimeManipulationEventHandler(TimeSpan elapsed); | |
public event TimeManipulationEventHandler TimeSkipOccured; | |
public event TimeManipulationEventHandler IsNextDay; | |
#endregion | |
#region Unity's | |
// Use this for initialization | |
void Start () { | |
if (_current == null) | |
_current = this; | |
else if (_current != this) | |
Destroy(gameObject); | |
DontDestroyOnLoad(this); | |
var now = DateTime.Now; | |
if (now.Date == lastCheck.Date.AddDays(1)) | |
OnIsNextDay(now - lastCheck); | |
} | |
// Update is called once per frame | |
void Update () { | |
var now = DateTime.Now; | |
var elapsed = now - lastCheck; | |
if (elapsed.TotalSeconds > 1) | |
OnTimeSkipOccured(elapsed); | |
lastCheck = now; | |
} | |
#endregion | |
#region Event Calls | |
void OnTimeSkipOccured(TimeSpan ts) | |
{ | |
if (TimeSkipOccured != null) | |
TimeSkipOccured(ts); | |
} | |
void OnIsNextDay(TimeSpan ts) | |
{ | |
if (IsNextDay != null) | |
IsNextDay(ts); | |
} | |
#endregion | |
#region Static Methods | |
public static TimeManipulation Initialize(long? lastCheck = null) | |
{ | |
if(_current == null) | |
{ | |
var go = new GameObject("TimeManager"); | |
var tm = go.AddComponent<TimeManipulation>(); | |
if (lastCheck != null) | |
tm.lastCheck = new DateTime(lastCheck.Value); | |
else tm.lastCheck = DateTime.Now; | |
return tm; | |
} | |
return _current; | |
} | |
public static long GetLastCheckTicks() | |
{ | |
if (_current != null) | |
return _current.lastCheck.Ticks; | |
else return 0; | |
} | |
#endregion | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment