I coded a bullet shooting system and when I click it spawns a lot of bullets, Please help me
Heres My Gun code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Gun : MonoBehaviour
{
public float damage = 10f;
public float range = 100f;
public float fireRate = 15f;
public float impactForce = 30f;
public Camera MainCamera;
public ParticleSystem GunShot;
public GameObject impactEffect;
public GameObject bulletPrefab;
public Transform bulletSpawn;
public float bulletSpeed = 30;
public float lifeTime = 3;
private float nextTimeToFire = 0f;
// Update is called once per frame
void Update()
{
if (Input.GetButton(“Fire1”))
{
Fire();
}
Heres my bullet code
using UnityEngine;
public class Bullet : MonoBehaviour
{
private void OnTriggerEnter(Collider other)
{
print("hit " + other.name + “!”);
Destroy(gameObject);
}
}
if (Input.GetButton(“Fire1”) && Time.time >= nextTimeToFire)
{
nextTimeToFire = Time.time + 1f / fireRate;
Shoot();
}
}
private void Fire()
{
GameObject bullet = Instantiate(bulletPrefab);
Physics.IgnoreCollision(bullet.GetComponent(),
bulletSpawn.parent.GetComponent());
bullet.transform.position = bulletSpawn.position;
Vector3 rotation = bullet.transform.rotation.eulerAngles;
bullet.transform.rotation = Quaternion.Euler(rotation.x, transform.eulerAngles.y, rotation.z);
bullet.GetComponent().AddForce(bulletSpawn.forward * bulletSpeed, ForceMode.Impulse);
StartCoroutine(DestroyBulletAfterTime(bullet, lifeTime));
}
private IEnumerator DestroyBulletAfterTime(GameObject bullet, float delay)
{
yield return new WaitForSeconds(delay);
Destroy(bullet);
}
void Shoot()
{
GunShot.Play();
RaycastHit hit;
if (Physics.Raycast(MainCamera.transform.position, MainCamera.transform.forward, out hit, range))
{
Debug.Log(hit.transform.name);
Target target = hit.transform.GetComponent();
if (target != null) ;
{
target.TakeDamage(damage);
}
if (hit.rigidbody != null)
{
hit.rigidbody.AddForce(-hit.normal * impactForce);
}
GameObject impactGO = Instantiate(impactEffect, hit.point, Quaternion.LookRotation(hit.normal));
Destroy(impactGO, 2f);
}
}
}