You need to understand a little more about coding in general and for unity in specific. What your code does right now is calling the Start function which is called once on the first frame the object is active which goes through the Shoot() function which shoots one bullet exactly. You haven’t actually implemented any system to use input from user or firing at a specific rate.
You need to give us more information about how you want the triggering of the firing to occur, but as for the firing itself you need to implement a delayed firing system which actually uses the fire rate variable. Something like this:
public Transform firePoint;
public GameObject bulletPrefab;
public float fireRate; //addition
private float nextfire; //addition
void Update()
{
if (Time.time >= nextfire){
Shoot();
}
}
public void Shoot()
{
nextfire = Time.time + fireRate;
Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
Debug.Log("Bang");
//Instantiate (flash, flashSpawn.position, flashSpawn.rotation); //addition
// GunShotSound.Play (); //addition
}
but when i start the game the
character fires once automatically
If you call Shoot(); in Start it shoots when game starts just remove that line. And where else do you use fireRate because there is no way to understand whether it works or not just these lines of code.
if (Input.GetButtonDown(“Fire1”) && Time.time > nextfire)
to start and made start public and connected the fire button to it. Thanks for your help anyway.
As for fire rate, I don’t use it in any other script and the only other script associated with firing is attached to the bullet and that covers speed, what it’s hit and destroying it after 4 frames
public float speed = 20f;
public Rigidbody rb;
// Use this for initialization
void Start()
{
rb.velocity = transform.forward * speed;
}
void OnTriggerEnter (Collider hitInfo)
{
Debug.Log(hitInfo.name);
}
// Update is called once per frame
void Update()
{
Destroy(gameObject, 4.0f);
}