Question by
Chyakka · Jan 30, 2017 at 01:23 AM ·
c#inputtime.deltatime
Making a timer on the press of a Key
I'm currently working on a reload function and when I call the GetKey which in this case is R it only does a single frame (I'm using time.deltatime) does anybody know a way to press a key and have it commence a timer (the reload timer) I'll paste the reload function below if that helps at all.
if (Input.GetKeyDown (KeyCode.R)) {
reloadTime = StatMaster.statM.gunSlot.itemReloadTime; {
if (reloadTime > 0) {
reloadTime -= Time.deltaTime * 1;
if (reloadTime <= 0) {
ammoCount = StatMaster.statM.gunSlot.itemAmmoCapacity;
reloadTime = 2.0f;
}
Comment
Best Answer
Answer by Pengocat · Jan 30, 2017 at 01:24 AM
You could use a coroutine that takes care of the delay something like this.
Coroutine reloadCoroutine;
void Update()
{
if (Input.GetKeyDown(KeyCode.R))
{
if (reloadCoroutine == null)
{
reloadCoroutine = StartCoroutine(Reload(StatMaster.statM.gunSlot.itemReloadTime));
}
}
}
IEnumerator Reload(float delay)
{
yield return new WaitForSeconds(delay);
ammoCount = StatMaster.statM.gunSlot.itemAmmoCapacity;
reloadCoroutine = null;
}
Thank you very much! Anything with IENumerators/Coroutines are not my forte sadly. Works great.