[Solved] Shotgun shooting c#

I this code, i don’t know how to make an Shotgun shooting type:
I have an Isometric game

if (weaponType == WeaponType.Rifle)
            {
                if (Physics.Raycast(shootRay, out shootHit, range, shootableMask))
                {
                    EnemyHealth enemyHealth = shootHit.collider.GetComponent<EnemyHealth>();

                    if (enemyHealth != null)
                    {
                        enemyHealth.TakeDamage(damagePerShot, shootHit.point);
                    }

                    gunLine.SetPosition(1, shootHit.point);

                    if (hitEffect != null)
                    {
                        Instantiate(hitEffect, shootHit.point, Quaternion.FromToRotation(Vector3.up, shootHit.normal));
                    }
                }
                else
                {
                    gunLine.SetPosition(1, shootRay.origin + shootRay.direction * range);
                }
            }
            else if (weaponType == WeaponType.Shoutgun)
            {

            }

You need to make a few rays and add slight offset to direction of each of them.
Since you didn’t post your entire script file, I can’t really modify your code.
The part you posted is missing declaration of “shootRay” variable.

1 Like

This is full code:

using UnityEngine;
using UnityEngine.UI;
using System.Collections;


[System.Serializable]
public class Ammunition
{
    [Tooltip("Remaining ammo")]
    public int carryingAmmo;
    [Tooltip("Ammo per clip")]
    public int clipAmmo;
    [Tooltip("Max ammo per clip")]
    public int maxClipAmmo;
}

public class Shooting : MonoBehaviour
{
    public enum ShootingLayers { All_Layers, Custom_Layers }
    public enum WeaponType { Rifle, Shoutgun }

    [Header("-Weapon Settings-")]
    public int damagePerShot = 20;
    public float timeBetweenBullets = 0.15f;
    public float range = 100f;
    public Transform gunEnd;
    public WeaponType weaponType;

    [Header("-Layers-")]
    public ShootingLayers shootingLayers;
    public LayerMask customShootingLayers;

    [Header("-Effects-"), Tooltip("Particle System or Bullet Hole, This is Optional")]
    public GameObject hitEffect;

    [Header("-Weapon Ammo-")]
    public float reloadDuration = 2.0f;
    public bool useAmmoUI = true;
    public Ammunition ammo;

    [Header("-Tags-")]
    public string playerTag = "Player";
    public string playerUITag = "PlayerUI";

    [Tooltip("Add the muzzleFlash particle in Firepoint as Child")]
    ParticleSystem muzzleFlash;
    [Tooltip("Add the gunLine in Firepoint")]
    LineRenderer gunLine;
    [Tooltip("Add the gunAudio in Firepoint")]
    AudioSource gunAudio;
    [Tooltip("Add the gunLight in Firepoint")]
    Light gunLight;

    float timer;
    Ray shootRay;
    RaycastHit shootHit;
    int shootableMask;
    float effectsDisplayTime = 0.2f;

    PlayerMovement playerMove;
    PlayerWeapons playerWeapons;

    PlayerUI playerUI;

    bool stopShooting;

    bool reload;

    void Awake()
    {
        shootableMask = customShootingLayers;

        gunLine = GetComponentInChildren<LineRenderer>();
        gunAudio = GetComponentInChildren<AudioSource>();
        gunLight = GetComponentInChildren<Light>();
        muzzleFlash = GetComponentInChildren<ParticleSystem>();
    }

    void Update()
    {
        playerMove = GameObject.FindWithTag(playerTag).GetComponent<PlayerMovement>() as PlayerMovement;
        playerWeapons = GameObject.FindWithTag(playerTag).GetComponent<PlayerWeapons>() as PlayerWeapons;

        playerUI = GameObject.FindWithTag(playerUITag).GetComponent<PlayerUI>() as PlayerUI;

        timer += Time.deltaTime;

        if (Input.GetButton("Fire1") && timer >= timeBetweenBullets)
        {
            if (ammo.clipAmmo <= 0)
                return;

            if (reload)
                return;

            if (stopShooting)
                return;

            Shoot();

            ammo.clipAmmo--;
        }

        if (timer >= timeBetweenBullets * effectsDisplayTime)
        {
            DisableEffects();
        }

        if(Input.GetButtonDown("Reload") && !reload)
        {
            Reload();
        }

        if (ammo.clipAmmo <= 0)
        {
            ammo.clipAmmo = 0;

            if (!reload)
            {
                Reload();
            }
        }

        if(playerWeapons.disableShooting)
        {
            if (playerMove.isRunning)
            {
                stopShooting = true;
            }
            else if (!playerMove.isRunning)
            {
                stopShooting = false;
            }
        }
        else if (!playerWeapons.disableShooting)
        {
            stopShooting = false;
        }

        updatePlayerUI();
    }

    public void DisableEffects()
    {
        gunLine.enabled = false;
        gunLight.enabled = false;
    }

    void Shoot()
    {

        timer = 0f;

        gunAudio.Play();

        gunLight.enabled = true;

        muzzleFlash.Stop();
        muzzleFlash.Play();

        gunLine.enabled = true;
        gunLine.SetPosition(0, gunEnd.position);

        shootRay.origin = transform.position;
        shootRay.direction = transform.forward;

        if (shootingLayers == ShootingLayers.All_Layers)
        {
            if (weaponType == WeaponType.Rifle)
            {
                if (Physics.Raycast(shootRay, out shootHit, range))
                {
                    EnemyHealth enemyHealth = shootHit.collider.GetComponent<EnemyHealth>();

                    if (enemyHealth != null)
                    {
                        enemyHealth.TakeDamage(damagePerShot, shootHit.point);
                    }

                    gunLine.SetPosition(1, shootHit.point);

                    if (hitEffect != null)
                    {
                        Instantiate(hitEffect, shootHit.point, Quaternion.FromToRotation(Vector3.up, shootHit.normal));
                    }
                }
                else
                {
                    gunLine.SetPosition(1, shootRay.origin + shootRay.direction * range);
                }
            }
            else if (weaponType == WeaponType.Shoutgun)
            {

            }
        }
        else if (shootingLayers == ShootingLayers.Custom_Layers)
        {
            if (weaponType == WeaponType.Rifle)
            {
                if (Physics.Raycast(shootRay, out shootHit, range, shootableMask))
                {
                    EnemyHealth enemyHealth = shootHit.collider.GetComponent<EnemyHealth>();

                    if (enemyHealth != null)
                    {
                        enemyHealth.TakeDamage(damagePerShot, shootHit.point);
                    }

                    gunLine.SetPosition(1, shootHit.point);

                    if (hitEffect != null)
                    {
                        Instantiate(hitEffect, shootHit.point, Quaternion.FromToRotation(Vector3.up, shootHit.normal));
                    }
                }
                else
                {
                    gunLine.SetPosition(1, shootRay.origin + shootRay.direction * range);
                }
            }
            else if (weaponType == WeaponType.Shoutgun)
            {

            }
        }
    }

    void Reload()
    {
        if (ammo.carryingAmmo <= 0 || ammo.clipAmmo == ammo.maxClipAmmo)
            return;

        reload = true;
        StartCoroutine(StopReload());
        print("Reloading");
    }

    IEnumerator StopReload()
    {
        yield return new WaitForSeconds(reloadDuration);
        LoadClip();
        reload = false;
        print("Reload Succesful");
    }

    public void LoadClip()
    {
        int ammoNeeded = ammo.maxClipAmmo - ammo.clipAmmo;

        if (ammoNeeded >= ammo.carryingAmmo)
        {
            ammo.clipAmmo = ammo.carryingAmmo;
            ammo.carryingAmmo = 0;
        }
        else
        {
            ammo.carryingAmmo -= ammoNeeded;
            ammo.clipAmmo = ammo.maxClipAmmo;
        }
    }

    void updatePlayerUI()
    {
        if (useAmmoUI)
        {
            if (!reload)
            {
                playerUI.ammoText.text = ammo.clipAmmo + "/" + ammo.carryingAmmo;
            }
            else if (reload)
            {
                playerUI.ammoText.text = "Reloading...";
            }
        }
    }
}

You need to define public float variable “bulletsSpread” and public int variable “bulletsPerShoot”, on top of your class.

//if weapon type is shotgun:
for (int i = 1; i <= bulletsPerShoot; i++)
{
      shootRay.direction = transform.forward+transform.up*Random.Range(-bulletsSpread, bulletsSpread);
      if (Physics.Raycast(shootRay, out shootHit, range)){
          //bullet effects and damage goes here
      }
}
1 Like

Thanks a lot, but can i make the bullets to shoot just on horizontal, right now is on Vertical and is an Isometric game.

You can zero out the axis that you want to be flat after creating the variable.

//if weapon type is shotgun:
for (int i = 1; i <= bulletsPerShoot; i++)
{
Vector3 randomDirection = new Vector3(transform.forward*Random.Range(-bulletsSpread, bulletsSpread));
randomDirection.x=0;
      shootRay.direction = transform.forward+randomDirection;
      
if (Physics.Raycast(shootRay, out shootHit, range)){
          //bullet effects and damage goes here
      }
}
1 Like

I have this error at line with new Vector3:
error CS1729: The type UnityEngine.Vector3' does not contain a constructor that takes 1’ arguments

I’m sorry I did not test the code. The idea though is to create a random vector3 rotation and then add it to shootRay.direction. But before doing that, zero out the axis that you want to remain 0;

1 Like

Ok, i solved, the problem was as new Vector3, i removed new Vector3 and is working, thanks!.

                    Vector3 randomDirection = transform.forward * Random.Range(-bulletsSpread, bulletsSpread);
                    randomDirection.x = 0;
                    shootRay.direction = transform.forward + randomDirection;

Thanks a lot: 1Piotrek1 and roger0.