I’m working on a simple game that relies on your total time in SECONDS ONLY to do some stuff. but Time.time gives me the value, but as a float.
I just need a way to get it as an int. or a way to convert it.
Here’s what I have so far:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class UserScoreTracker : MonoBehaviour
{
//the amount of time it took to finish the level. its the TIME, but its called score.
public int score = 0; // <-- NEEDS TO BE INT!!!!!
private bool Aktive; //heh lol "Aktive" XD
//the username input box/and where to store it and also waht to do with it.
public string username;
public GameObject ScoreUI;
public void UserInput(InputField userField)
{
username = userField.text;
}
public void Update()
{
score = Time.time;
}
public void SubmitSkcoar()
{
Highscores.AddNewHighscore(username,score);
}
public void OnTriggerEnter()
{
ScoreUI.SetActive(true);
}
}
You still want the timer to count as a float, because that is what time is. However, when you get the value out of your score (time) float you can convert it into int seconds.
As people come and read, I like to add another solution for a counter.
The advantage in this solution is, that the Coroutine doesn’t run in the Update method and won’ be called every single frame.
This code will increase your score (time needed) variable every second by 1.
public int score = 0;
void Start()
{
StartCoroutine( TimerRoutine() );
}
IEnumerator TimerRoutine ()
{
WaitForSeconds delay = new WaitForSeconds(1);
while (true)
{
score += 1;
yield return delay;
}
}
When the level is finished and you put your score in the scoreboard, you should stop the counter with
which mine does not for some reason, you can use this code instead to convert a float to an int. I’m using Visual Studio 2017 C# compiler
public float timer = 0.0f;
public int seconds;
void Update()
{
// seconds in float
timer += Time.deltaTime;
// turn seconds in float to int
seconds = (int)(timer % 60);
print(seconds);
}
float timer = 0.0f;
int seconds ;
void Update()
{
timer += Time.deltaTime;
seconds = Convert.ToInt32( timer % 60);// you can use the seconds wherever you wish
}