- Home /
Question by
YUNGOD · Jun 30, 2018 at 04:37 PM ·
c#animationscripting beginner
Run animation when countdown reaches 0
hey i am making a game in which i have 5 seconds to tap as fast as i can on the screen i have made a countdown timer but when the timer becomes 0 i want to play a animation or debug something but its not happening please help this is my script using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class CountDown : MonoBehaviour
{
float timeLeft = 5.0f;
public Text text;
void Update()
{
timeLeft -= Time.deltaTime;
text.text = "" + Mathf.Round(timeLeft);
}
}
Comment
you should consider improving the formatting of your questions to make it easy for people to answer them...
Answer by Ermiq · Jun 30, 2018 at 02:58 PM
Well, you have to check if timeLeft is zero and call some methods then. Something like this:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class CountDown : MonoBehaviour
{
float timeLeft = 5.0f;
public Text text;
void Update()
{
timeLeft -= Time.deltaTime;
text.text = "" + Mathf.Round(timeLeft);
//Here the game will check if time is expired
if (Mathf.Round (timeLeft) == 0f)
{
// A name of a method you want to call when time is expired
DoSomethingWhenTimeIsOver ();
//or do something right here
Debug.Log ("This is a code in Update() method");
}
}
// This method will be called when rounded 'timeLeft' is zero
private void DoSomethingWhenTimeIsOver ()
{
// Print message in Unity's debug console
Debug.Log ("This is a code in DoSomethingWhenTimeIsOver() method");
}
}
Also, I guess he just should use a property and an event and subscribe methods to it like this...
public event Actio<float> TimeEnded;
private float timeLeft;
public float TimeLeft
{
get
{
return timeLeft;
}
set
{
timeLeft = value;
if (value < 1f)
{
TimeEnded?.Invoke(value);
}
}
}
private void Start()
{
TimeEnded += (time) => {
// Do something with time...
};
}
Answer by WinterboltGames · Jun 30, 2018 at 02:39 PM
Use this code...
public class Timer : MonoBehaviour
{
// The time left.
public float timeLeft = 5f;
// How many seconds are considered a tick?
public float tickRate = 1f;
// Counter...
private float counter;
// You don't need to make Update() public.
private void Update()
{
// Check if the counter has reached the tick rate.
if (counter >= tickRate)
{
// Log 'Tick!' to the console every 'tickRate' seconds...
Debug.Log("Tick!");
// reset the counter.
counter = 0f;
}
counter += Time.deltaTime;
}
}