how to add shoot cooldown
I want to add shoot cooldown to my single shot gun
how do i do it
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using TMPro;
public class SingleShotGun : MonoBehaviour
{
public TMP_Text hitText;
public float damage = 10f;
public float range = 100f;
bool shot;
public Camera fpsCam;
public GameObject hitmarker;
public float shotsFired;
public float shotsHit;
void Start()
{
shot = false;
}
// Update is called once per frame
void Update()
{
if(Input.GetButtonDown("Fire1"))
{
SingleShotShoot();
}
if(shot)
{
StartCoroutine("hitmarkerShow");
}
hitText.text = shotsHit + "/" + shotsFired;
}
void SingleShotShoot()
{
shotsFired += 1;
RaycastHit hit;
if(Physics.Raycast(fpsCam.transform.position, fpsCam.transform.forward, out hit, range))
{
Debug.Log(hit.transform.name);
shot = true;
shotsHit += 1;
}
}
IEnumerator hitmarkerShow()
{
hitmarker.SetActive(true);
yield return new WaitForSeconds(0.05f);
hitmarker.SetActive(false);
shot = false;
}
}
help
Comment
Answer by FaffyWaffles · May 01, 2021 at 01:23 PM
just use another coroutine, here is some example code
public class CooldownControllerExample : MonoBehaviour
{
public float attackCooldown;
private bool cool = true;
public void CooldownStart()
{
StartCoroutine(CooldownCoroutine());
}
IEnumerator CooldownCoroutine()
{
cool = false;
yield return new WaitForSeconds(attackCooldown);
cool = true;
}
}
call CoolDownStart(); when you want to, well, start the cooldown. assign attackCooldown in the inspector. if bool is true, gun is cool
Your answer
![](https://koobas.hobune.stream/wayback/20220613024643im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Any Suggestions for how I could improve the gun cooldown? 0 Answers
Shotguns with raycasts 0 Answers
Hitmarker still shows while reloading 0 Answers
FPS Gun Hold 0 Answers
Can i make automatic fire? 0 Answers