- Home /
Question by
iEnzo · Feb 03, 2019 at 04:50 AM ·
scripting beginnerscriptingbasics
What script should I use to make a countdown timer bar?
I want to program an 8 second Countdown bar that refills within 10 seconds over and over. When refilling, all mouse button inputs are disabled and are re-enabled within the 8 second countdown. How can I program this?
Comment
Answer by JaredHD · Feb 03, 2019 at 10:56 AM
Hi,
You can try this script. Create a new c# script called CountDownBar. Attach the below code to it. Save and go to Unity. Add the script to a gameobject.
In the inspector create a Slider. And attach the slider to the script. Press play and the slider should go up and down.
using UnityEngine;
using UnityEngine.UI;
public class CountDownBar : MonoBehaviour
{
public static bool allowInputs;
public Slider countdownBar;
private bool countDown = true;
public float countDownTime = 8;
public float refillTime = 10;
private void Start()
{
//Set the max value to the refill time
countdownBar.maxValue = refillTime;
}
private void Update()
{
if (countdownBar.maxValue != refillTime)
countdownBar.maxValue = refillTime;
if (countDown) //Scale the countdown time to go faster than the refill time
countdownBar.value -= Time.deltaTime / countDownTime * refillTime;
else
countdownBar.value += Time.deltaTime;
//If we are at 0, start to refill
if (countdownBar.value <= 0)
{
countDown = false;
allowInputs = false;
}
else if (countdownBar.value >= refillTime)
{
countDown = true;
allowInputs = true;
}
}
}
To prevent inputs, go to the script that uses inputs, and just before it add a check if you can allow inputs.
void CheckInput()
{
if (!CountDownBar.allowInputs)
return;
//Your code for handling inputs
}
And that should be it.
Hope that helps