I am trying to create a 60 second timer. Here is my code. When I play my game it gives me a decimal, but I want a whole number. Please help!
using UnityEngine;
using TMPro;
using UnityEngine.SceneManagement;
public class Timer : MonoBehaviour {
public TMP_Text timer;
public float timerValue = 60f;
void Update()
{
timerValue -= Time.time;
timer.SetText(timerValue.ToString());
}
}
Check out the C# docs for the .ToString() method… you can optionally supply a string formatting argument to force it to only render as integers, or put commas, or whatever else.
I don’t understand. Can you please give me a line of code so I can understand.
This explains how standard numeric format strings work, and has several examples of how to use them:
But in this case, you’d probably be better off explicitly converting the float to an int before doing anything else, because that way you can add in a condition that prevents ToString from being called at all if the int is the same as last frame. This will prevent a lot of unnecessary memory allocation.
Your code also uses Time.time where I’m pretty sure you meant Time.deltaTime.
Putting a single hash in ToString(“”) outputs it to that - result is no decimals and a whole number
timer.SetText(timerValue.ToString("#"));