- Home /
How do you make a countdown timer that will lose time if you press a button?
I can find numerous tutorials online about how to make a simple countdown timer in Unity, but none about how to subtract time from it if you press a button.
I am making a 2-D platformer game where if your character passes in front of an NPC, it brings up dialog. I want to make so that one option of dialog does nothing to the timer, but the other option will subtract 10 seconds from the timer. How do I do this?
$$anonymous$$y current timer is modeled after this one: https://www.noob-programmer.com/unity3d/countdown-timer/
public float timer = 30;
void Update(){
timer -= Time.deltaTime;
if (Input.any$$anonymous$$eyDown) {
timer = timer -1;
}
}
Answer by hassanyawar · Oct 30, 2018 at 12:36 PM
private float timer;
private Button targetButton;
void Awake ()
{
timer = 50f;
// this line below only in case if you don't assign the SubtractTime method
// to button from inspector otherwise comment this line
targetButton.onClick.AddListener( () => SubtractTime() );
}
void Update ()
{
timer -= Time.deltaTime;
}
// Add this function to a button's onClick event
public void SubtractTime ()
{
timer -= 10f;
}
Your answer
Follow this Question
Related Questions
How to make reverse countdown timer in unity? 1 Answer
Reload level after timer hits 0 1 Answer
Speed up timer 1 Answer
Stop and Pause Timer 2 Answers
timer not ticking down 2 Answers