Friday, June 17, 2016

unity - Why the timer is not showing the hours?


It's showing minutes seconds milliseconds but I want to show also the hours.


At the top:


private int seconds; // Seconds.

private int minutes; // Minutes.
private int hours; // Hours.

In Update:


void Update()
{
if (seconds < 1)
{
seconds = 59;
minutes--;

}
if (minutes < 1)
{
minutes = 59;
hours--;
}
if (hours < 1)
{
hours = 59;
}

seconds--;

EditorGUILayout.LabelField("Next: ", hours.ToString() + ":" + minutes.ToString() + ":" + seconds.ToString());

Update, This is what I tried:


using System;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEditor.SceneManagement;

using UnityEngine;
using UnityEngine.SceneManagement;

public class Timer : EditorWindow
{

private static Timer editor;
private static int width = 300;
private static int height = 110;
private static int x = 0;

private static int y = 0;
int totalSeconds;

[MenuItem("Window/Timer")]
static void ShowEditor()
{
editor = EditorWindow.GetWindow();
editor.Init();
}


public void Init()
{
StartTimer(1, 1, 50);
Debug.Log("The level will now be saved automatically");
}

void OnGUI()
{
EditorGUILayout.LabelField("Next: ", TimeString());
}


public void StartTimer(int hours, int minutes, int seconds)
{
totalSeconds = seconds + 60 * minutes + 60 * 60 * hours;
}

string TimeString()
{
return string.Format("{0:00}:{1:00}:{2:00}",
totalSeconds / (60 * 60), // Hours

(totalSeconds / 60) % 60, // Minutes
totalSeconds % 60); // Seconds
}
}

But the timer is not moving not counting back it stay still. I tried also to move the line:


StartTimer(1, 1, 50);

To be inside the OnGUI before the LabelField.



Answer




Writing your own date and time handling code from scratch is a path towards agony and despair. It is usually far better to use the time handling features provided by your platform. In the case of C#, the standard library offers you a handy TimeSpan class.


 TimeSpan timer = new TimeSpan(1, 1, 50);
Debug.Log("The timer is set to " + timer.ToString("hh\\:mm\\:ss"));

The class also has a bunch of methods which allow you to modify the value in an easy and painless way. For example, if you want the Update method of a MonoBehaviour to reduce the remaining time:


 Update() {
TimeSpan deltaTimeSpan = TimeSpan.FromSeconds(Time.deltaTime);
timer = timer.Subtract(deltaTimeSpan);
Debug.Log("Time left: " + timer.ToString("hh\\:mm\\:ss"));
}

No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...