This code shows me seconds and miliseconds after game started. What should I do because I want to show only seconds ?
using UnityEngine; using System.Collections; using UnityEngine.UI;
public class TimerScript : MonoBehaviour {
public Text timerText;
private float secondsCount;
private int count;
// Use this for initialization
void Start () {
count = 0;
}
// Update is called once per frame
void Update () {
count = count + 1;
secondsCount += Time.deltaTime;
timerText.text =" Score:" + secondsCount.ToString();
}
Answer by Pengocat · Jan 26, 2017 at 12:58 AM
You could simply use Time.time like this. The zero in "Score:0"
is what removes the milliseconds/decimals.
using UnityEngine;
using UnityEngine.UI;
public class TimerScript : MonoBehaviour
{
public Text timerText;
void Update()
{
timerText.text = Time.time.ToString ("Score:0");
}
}
That works but with that code time doesn't restart when player dies , and with my code above did.
How can I call Text from TimerScript to script where is function to restartlevel ? I know for gameobjects but I don't now how to call this text to restart to 0 when player dies
In the timer script you could have a public method to reset the timer.
using UnityEngine;
using UnityEngine.UI;
public class TimerScript : $$anonymous$$onoBehaviour
{
public Text timerText;
float timer;
void Update()
{
timer += Time.deltaTime;
timerText.text = timer.ToString("Score:0");
}
public void ResetTimer()
{
timer = 0;
}
}
Then in anotherScript where you have the method that happens when the player is dead you call the method in TimerScript. In order to get the reference to the instance of TimerScript you drag TimerScript onto the public field timerScript in AnotherScript in the inspector.
using UnityEngine;
public class AnotherScript : $$anonymous$$onoBehaviour
{
public TimerScript timerScript;
public void PlayerDeath()
{
timerScript.ResetTimer();
}
}
Your answer
Follow this Question
Related Questions
Count Down Timer 1 Answer
timer stopwatch 2 Answers
Saving and displaying best time per level. 1 Answer