using UnityEngine;
using UnityEngine.UI;
// Sci-Fi Ship Controller. Copyright (c) 2018-2023 SCSM Pty Ltd. All rights reserved.
namespace SciFiShipController
{
///
/// On-screen timer.
/// NOTE: This will inpact Garbage Collection (GC) as the on-screen text is updated
/// with stringbuilder.
///
public class OnScreenTimer : MonoBehaviour
{
#region Public Variables and Properties
public bool initialiseOnAwake = true;
public float dayLength = 86400f; // Day length in seconds
public Color screenClockTextColour = new Color(240f / 255f, 240f / 255f, 240f / 255f, 33f / 255f);
public bool useScreenClockSeconds = true;
// Screen clock defaults
public Color GetDefaultScreenClockTextColour { get { return new Color(240f / 255f, 240f / 255f, 240f / 255f, 33f / 255f); } }
#endregion
#region Private variables
private bool isInitialised = false;
private Canvas timerCanvas = null;
private float dayTimer = 0f;
private float screenClockUpdateTimer = 0f;
private float screenClockUpdateInterval = 60f; // # seconds between updates
private float simTimeRealTimeRatio = 1f; // How many seconds pass in simulated time to every real time second?
private RectTransform screenClockPanel;
private Text screenClockText;
#endregion
#region Initialisation Methods
// Use this for initialization
void Awake()
{
if (initialiseOnAwake) { Initialise(); }
}
///
/// WARNING: This will affect GC as it does string comparisons
///
public void Initialise()
{
isInitialised = false;
ValidateOnScreenTimer();
// How many seconds pass in simulated time to every real time second?
simTimeRealTimeRatio = 86400 / dayLength;
// Determine how often to update the clock
screenClockUpdateInterval = useScreenClockSeconds ? 1f : 60f;
if (screenClockText != null)
{
screenClockText.text = CurrentTimeString(useScreenClockSeconds);
UpdateScreenClockColour();
isInitialised = true;
}
}
#endregion
#region Update Methods
// Update is called once per frame
void Update()
{
dayTimer += Time.deltaTime;
if (isInitialised && screenClockText != null)
{
// Clock displays hours and minutes. So need no to update every frame
screenClockUpdateTimer += Time.deltaTime * simTimeRealTimeRatio;
if (screenClockUpdateTimer > screenClockUpdateInterval)
{
screenClockUpdateTimer = 0f;
screenClockText.text = CurrentTimeString(useScreenClockSeconds);
}
}
}
#endregion
#region Private Methods
private void ValidateOnScreenTimer()
{
if (timerCanvas == null)
{
// Attempt to find the canvas
GameObject timerCanvasGO = null;
Canvas[] canvasArray = FindObjectsOfType