So I’m currently just messing around learning how to use Unity. I created a cube that is supposed to shoot squares. The problem is that the code I’ve set up needs some way of telling the scripts not to create 30 bullets per second, but instead create 1 bullet every 0.5 seconds.
using UnityEngine;
using System.Collections;
public class Shoot : MonoBehaviour {
public GameObject bullet;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetKey ("space"))
Instantiate (bullet, transform.position, transform.rotation);
}
}
Is there a way to do this? Because currently if I hold down space it creates 30 bullets every second. I need a way to limit it to 2 bullets every second.
using UnityEngine;
using System.Collections;
public class Shoot : MonoBehaviour {
public GameObject bullet;
private const float SHOOT_INTERVAL = 0.5f;
private float _ShootTimer = 0;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetKey("space"))
{
_ShootTimer += Time.deltaTime;
if (_ShootTimer > SHOOT_INTERVAL)
{
Instantiate (bullet, transform.position, transform.rotation);
_ShootTimer = 0;
}
}
else
{
_ShootTimer = 0;
}
}
}
Here’s another way to skin the cat
private bool canExecute = true;
private float coolDownSeconds = 1.0f;
void Update()
{
if (Input.GetKeyDown(KeyCode.Space) && canExecute)
{
StartCoroutine(ShootWithCoolDown());
}
}
private IEnumerator ShootWithCoolDown()
{
canExecute = false;
Instantiate(bullet, transform.position, transform.rotation);
yield return new WaitForSeconds(coolDownSeconds);
canExecute = true;
}
Here is one more way to skin the cat:
private float coolDownSeconds = 1.0f;
void Start()
{
StartCoroutine(ShootWithCoolDown());
}
private IEnumerator ShootWithCoolDown()
{
while(true) {
if (Input.GetKeyDown(KeyCode.Space)) {
Instantiate(bullet, transform.position, transform.rotation);
yield return new WaitForSeconds(coolDownSeconds);
continue;
}
yield return null;
}
}