how to create weapon shooting C# script in unity

 Creating a weapon system is a complex process which involves many step and deep knowledge of various unity aspect like physics, input system, collision, animation, and many more. In this post we are going to create a very simple working weapon system and other with some extended features.

Follow these steps to create a simple weapon system:

  1. Create a new C# script in unity and name it whatever you want.
  2. Declare a public variable  public GameObject bulletPrefab; for representing bullet prefab which will instantiated when we fire weapon.
  3. We will if user mouse button by Input.GetMouseButtonDown(0) method inside if statement in Update() function.
  4. We use Instantiate() method to create an instance of bullet prefab at position and rotation of weapon inside this if statement and store reference to this prefab in a variable. 
  5. Now we access bullet Rigidbody component by GetComponent method and then AddForce in it. After that play shooting audion.
  6. Attach this script to our weapon in scene and drag and drop bullet prefab into it.
  7. Make sure you added a Rigidbody component in our bullet prefab.
  8. Add a AudioSource component in weapon gameObject and then add your weapon shooting audio in AudioClip field.

Our script will be following:

Code :
using UnityEngine;

public class WeaponShooter : MonoBehaviour
{
    public GameObject bulletPrefab;
    public AudioSource shootSound;

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            // Instantiate bullet prefab at position and rotation of weapon
            GameObject bullet = Instantiate(bulletPrefab, transform.position, transform.rotation);
            // Apply force to bullet in forward direction of weapon
            bullet.GetComponent<Rigidbody>().AddForce(transform.forward * 1000);
            // Play shooting sound
            shootSound.Play();
        }
    }
}


Advanced weapon shooting

Below is an example for creating a liltle more advanced weapon system for unity game:

Code :
using UnityEngine;

public class Weapon : MonoBehaviour
{
    public GameObject projectilePrefab;
    public Transform muzzle;
    public float fireRate = 0.5f;
    private float fireTimer;
    public AudioClip shootingSound;
    public AudioSource audioSource;
    public ParticleSystem muzzleFlash;
    public int ammo = 30;
    public int maxAmmo = 30;
    public int reloadTime = 2;
    public bool reloading = false;
    public GameObject reloadCanvas;
    private float reloadTimer;
    public float bulletSpeed = 50f;

    void Update()
    {
        if (Input.GetButton("Fire1"))
        {
            if (fireTimer <= 0 && ammo > 0 && !reloading)
            {
                Fire();
                fireTimer = fireRate;
                ammo--;
            }
        }
        fireTimer -= Time.deltaTime;
        if (Input.GetKeyDown(KeyCode.R) && ammo < maxAmmo && !reloading)
        {
            reloading = true;
            reloadCanvas.SetActive(true);
            reloadTimer = reloadTime;
        }
        if (reloading)
        {
            reloadTimer -= Time.deltaTime;
            if (reloadTimer <= 0)
            {
                reloading = false;
                reloadCanvas.SetActive(false);
                ammo = maxAmmo;
            }
        }
    }

    void Fire()
    {
        audioSource.PlayOneShot(shootingSound);
        muzzleFlash.Play();
        GameObject bullet = Instantiate(projectilePrefab, muzzle.position, muzzle.rotation);
        Rigidbody rb = bullet.GetComponent<Rigidbody>();
        rb.AddForce(muzzle.forward * bulletSpeed, ForceMode.VelocityChange);
    }
}

Attach this gameObject to weapon gameObject. In this example we add few more features like firing rate, max amino and many more. Concept for firing bullet is quit same as early example.

  • projectilePrefab variable will reference to our bullet prefab which we want to instantiate when we fire weapon.
  • muzzle variable will reference to transform component of weapon muzzle. transform from where we want to instantiate our bullet in weapon.
  • fireRate is the time after which we can fire next bullet.
  • fireTime variable is for tracking of time between wepon shots.
  • shootingSound variable is for referencing to audio clip we want to play when weapon fire.
  • audioSource variable will reference to AudioSource component of weapon object.
  • muzzleFlash variable will reference to ParticleSystem component which will play muzzle flash effect when weapon is fired.
  • ammo variable will track remaining ammo.
  • maxAmmo variable is maximum ammo that weapon can hold.
  • reloadTime variable is time which weapon take to reload.
  • reloading variable is a boolean which keep track that whether weapon is currently reloading or not.
  • reloadCanvas variable will reference to canvas which display reloading text or animation.
  • In Update() function we check if player is pressing "Fire1" button (it is unity default input - mouse 0 and left ctrl button) and if fire timer is less or equal to 0. If both conditions are true then we call fire function to fire bullet and set fire time to fire rate.
  • Fire function will instantiate bullet at muzzle position and rotation and muzzle flash effect.
  • You can press R key for reloading ammo.

weapon shooting in unity

You must note that this is a simple example and you can modify this script according your game requirements.


Comments