im using unity 5.6.0 for this btw. i have 2 problems with invoke repeating, first of all it wont stop creating objects after i let go of spacebar, second no matter what i change the firing rate to it always comes out super fast and wont slow down. heres my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class projectile : MonoBehaviour {
public GameObject bulleet;
public float firingrate = 0.2f;
// Use this for initialization
void Start () {
}
void fire()
{
GameObject bulet = Instantiate(bulleet, transform.position, Quaternion.identity) as GameObject;
Rigidbody bullet = bulet.GetComponent<Rigidbody>();
bullet.velocity = transform.forward * 500 * Time.deltaTime;
}
// Update is called once per frame
void Update () {
if (Input.GetKey(KeyCode.Space))
{
InvokeRepeating("fire" , 0.0000001f, firingrate);
}
}
}
InvokeRepeating goes forever (it repeats at firingrate) for each time you call it. Instead you’ll want to start a coroutine in Start that loops, something roughly like this:
IEnumerator MyCoroutine() {
while(true) {
yield return new WaitForSeconds(firingrate);
if (Input.GetKey(KeyCode.Space))
fire();
}
}
I would think this should do. It does not check for ammo so you’d need to add that.
First, you press, it shoots. It also sets the timer to firingrate. Next frame, you hold the button down, it will decrease timer and check if it is lower than 0. If not, it won’t do anything until timer is decreased enough so it is negative. At that point, it will fire and set it back to firingrate so it will wait again.