Need help with my code

So when I click my mouse button it shoots loads of ammo in different directions, what I want it to do is shoot one bullet and shoot to the direction I want it to

Here is 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 Transform bullet;
public Transform bulletSpawner;

public Camera MainCamera;
public ParticleSystem GunShot;
public GameObject impactEffect;
public GameObject bulletPrefab;
private float nextTimeToFire = 0f;

// Update is called once per frame
void Update()
{
if (Input.GetButton(“Fire1”))
{
Shoot();
}

if (Input.GetButton(“Fire1”) && Time.time >= nextTimeToFire)
{
nextTimeToFire = Time.time + 1f / fireRate;
Shoot();
}
}

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);

Instantiate(bullet, bulletSpawner.position, bulletSpawner.rotation);
}
}
}

Here is my Bullet code

using System;
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography;
using UnityEngine;

public class Bullet : MonoBehaviour
{
public Rigidbody myRigidbody;
public float forceMin;
public float forceMax;

float lifetime = 4;
float fadetime = 2;

// Start is called before the first frame update
void Start()
{
float force = UnityEngine.Random.Range(forceMin, forceMax);
myRigidbody.AddForce(transform.right * force);
myRigidbody.AddTorque(UnityEngine.Random.insideUnitSphere * force);

StartCoroutine (Fade ());
}

IEnumerator Fade()
{
yield return new WaitForSeconds(lifetime);

float percent = 0;
float fadeSpeed = 1 / fadetime;
Material mat = GetComponent().material;
Color initialColour = mat.color;

while (percent < 1)
{
percent += Time.deltaTime * fadeSpeed;
mat.color = Color.Lerp(initialColour, Color.clear, percent);
yield return null;
}

Destroy(gameObject);
}
}

With code that long, you’re probably not going to get help without using code tags.

1 Like