Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

CoD Modern Warfare style gun script (update 08/07/2015)

Discussion in 'Scripting' started by novashot, Jun 27, 2010.

  1. novashot

    novashot

    Joined:
    Dec 12, 2009
    Posts:
    373
    Update 8/7/2015 (yeah...it's about time)

    Since people are still using this apparently and the thread gets pinged once in a while... it is about time to update the code. Since this was my first post and attempt into Unity scripting way back when... the gun was OK (but pretty crap code). Here are some updated scripts (better code, gun still OK)...

    I moved from a single script for all guns approach to a more inherited approach. All of my guns now inherit from my base Gun script. Each child is a different kind of gun but in your code you can still grab it using the base Gun class.

    As usual... use these as you see fit and how every you want. If you like them or the end up in something cool.. post back (or pm/mail) and let me see... would be cool to see it actually being used somewhere.


    Link to a newer blah webplayer (built today with these scripts)
    https://dl.dropboxusercontent.com/u/1475775/CoD/newer/08-07-2015/gun.html



    Gun.cs
    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5.  
    6. [System.Serializable]
    7. public class Damage
    8. {
    9.     public int amount; // how much damage
    10.     public DamageType type; //what type of damage
    11. }
    12.  
    13. public enum DamageType
    14. {
    15.     NORMAL,
    16.     FIRE,
    17.     ICE,
    18.     ACID,
    19.     ELECTRIC,
    20.     POISON
    21. }
    22.  
    23. public enum WeaponType
    24. {
    25.     SEMIAUTO, // burst fire and shotguns fall under this category
    26.     FULLAUTO
    27. }
    28.  
    29.  
    30. public class Gun : MonoBehaviour {
    31.     public string weaponName;                         // Name of this weapon
    32.     public WeaponType typeOfWeapon;             // type of weapon, used to determine how the trigger acts
    33.     public bool usePooling = false;             // do we want to use object pooling or instantiation
    34.     public Damage damage = new Damage();        // the damage and type of damage this gun does
    35.     public float projectileSpeed = 100.0f;      // speed that projectile flies at
    36.     public float projectileForce = 10.0f;       // force applied to any rigidbodies the projectile hits
    37.     public float projectileLifeTime = 5.0f;     // how long before the projectile is considered gone and recycleable
    38.  
    39.     public Transform muzzlePoint = null;        // the muzzle point for this gun, where you want bullets to be spawned
    40.  
    41.     public int maxPenetration = 1;              // maximum amount of hits detected before the bullet is destroyed
    42.     public float fireRate = 0.5f;               // time betwen shots
    43.  
    44.     public bool infinteAmmo = false;            // gun can have infinite ammo if thats what you wish
    45.     public int roundsPerClip = 50;              // number of bullets in each clip
    46.     public int ammoReserve = 200;               // number of clips you start with    
    47.     public int roundsLeft;                      // bullets in the gun-- current clip
    48.  
    49.     public float reloadTime = 2.5f;             // how long it takes to reload in seconds
    50.     protected bool isReloading = false;         // are we currently reloading
    51.  
    52.     public float baseSpread = 0.2f;             // how accurate the weapon starts out... smaller the number the more accurate
    53.     public float maxSpread = 4.0f;              // maximum inaccuracy for the weapon
    54.     public float spreadPerShot = 0.75f;         // increase the inaccuracy of bullets for every shot
    55.     public float spread = 0.0f;                 // current spread of the gun
    56.     public float decreaseSpreadPerTick = 0.25f;  // amount of accuracy regained per frame when the gun isn't being fired
    57.     public float spreadDecreaseTicker = 0.5f;   // time in seconds to decrease inaccuracy
    58.  
    59.     protected float nextFireTime = 0.0f;        // able to fire again on this frame
    60.     protected bool spreadDecreasing = false;    // is the gun currently decrasing the spread
    61.  
    62.     protected ProjectileInfo bulletInfo = new ProjectileInfo(); // all info about gun that's sent to each projectile
    63.  
    64.  
    65.     protected virtual void Start()
    66.     {
    67.         roundsLeft = roundsPerClip; // load gun on startup      
    68.     }
    69.  
    70.     // all guns handle firing a bit different so give it a blank function that each gun can override
    71.     public virtual void Fire()
    72.     {
    73.  
    74.     }
    75.  
    76.    
    77.     // everything fires a single round the same
    78.     protected virtual void FireOneShot() {
    79.        
    80.     }
    81.  
    82.     // reload your weapon
    83.     protected virtual IEnumerator Reload()
    84.     {
    85.         if (isReloading)
    86.         {
    87.             yield break; // if already reloading... exit and wait till reload is finished
    88.         }
    89.  
    90.         if (ammoReserve > 0)
    91.         {
    92.             isReloading = true; // we are now reloading
    93.             int roundsNeeded = roundsPerClip - roundsLeft; // how many rounds needed to fill the gun
    94.             yield return new WaitForSeconds(reloadTime); // wait for set reload time
    95.  
    96.             if (ammoReserve < roundsNeeded)
    97.             {
    98.                 roundsNeeded = ammoReserve;// if we have less bullets than needed to fill the gun... put all we have in
    99.             }
    100.  
    101.             roundsLeft += roundsNeeded; // fill up the gun
    102.         }
    103.  
    104.         isReloading = false; // done reloading
    105.     }
    106.  
    107.  
    108.     void DecreaseSpread()
    109.     {
    110.         // decrease the current spread per tick
    111.         spread -= decreaseSpreadPerTick;
    112.  
    113.         // if the current spread is less then the base spread value, set it to the base
    114.         if (spread <= baseSpread)
    115.         {
    116.             spread = baseSpread;
    117.  
    118.             // stop the decrease spread function until we need it again
    119.             spreadDecreasing = false;
    120.             CancelInvoke("DecreaseSpread");
    121.         }
    122.     }
    123.  
    124.     // set all bullet info from the gun's info
    125.     // if you plan to be able to change weapon stats on the fly
    126.     // call this function in the fire function (worst performance but always checkes gun stats before firing)
    127.     // or Always call this just after altering a weapon's stats (best performance since its called once when it's needed)
    128.     // default right now is it is called once in start
    129.     protected void SetupBulletInfo()
    130.     {
    131.         bulletInfo.owner = transform.root.gameObject;   // the Owner of this weapon (GameObject) <- use this for scoreboard and who killed who
    132.         bulletInfo.name = name;                         // Name of this weapon  <- for keeping track of weapon kills / whose killed by what
    133.         bulletInfo.damage.amount = damage.amount;       // amount of damage
    134.         bulletInfo.damage.type = damage.type;           // type of damage
    135.         bulletInfo.force = projectileForce;             // weapon force
    136.         bulletInfo.maxPenetration = maxPenetration;     // max hits
    137.         bulletInfo.maxSpread = maxSpread;               // max weapon spread
    138.         bulletInfo.spread = spread;                     // current weapon spread value
    139.         bulletInfo.speed = projectileSpeed;             // projectile speed
    140.         bulletInfo.owner = transform.root.gameObject;   // this projectile's owner gameobject, useful if you want to know whose killing what for kills/assists or whatever
    141.         bulletInfo.usePool = usePooling;                // do we use object pooling
    142.         bulletInfo.projectileLifeTime = projectileLifeTime; // how long till this bullet just goes away
    143.     }
    144.    
    145. }
    146.  
    Gun_Physical.cs (since physical and raycast guns behave differently)
    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5. public class Gun_Physical : Gun {
    6.     public GameObject projectile = null;        // projectile prefab... whatever this gun shoots
    7.    
    8.  
    9.     protected override void Start()
    10.     {
    11.         base.Start();
    12.         SetupBulletInfo(); // set a majority of the projectile info
    13.     }
    14.    
    15.     protected override void FireOneShot () {
    16.         if (roundsLeft > 0)
    17.         {
    18.             Vector3 pos = muzzlePoint.position; // position to spawn bullet is at the muzzle point of the gun      
    19.             Quaternion rot = muzzlePoint.rotation; // spawn bullet with the muzzle's rotation
    20.  
    21.             bulletInfo.spread = spread; // set this bullet's info to the gun's current spread
    22.             GameObject newBullet;
    23.  
    24.             if (usePooling)
    25.             {
    26.                 newBullet = ObjectPool.pool.GetObjectForType(projectile.name, false);
    27.                 newBullet.transform.position = pos;
    28.                 newBullet.transform.rotation = rot;
    29.             }
    30.             else
    31.             {
    32.                 newBullet = Instantiate(projectile, pos, rot) as GameObject; // create a bullet
    33.                 newBullet.name = projectile.name;
    34.             }
    35.  
    36.             newBullet.GetComponent<Projectile>().SetUp(bulletInfo); // send bullet info to spawned projectile
    37.  
    38.             spread += spreadPerShot;  // we fired so increase spread
    39.  
    40.             // if the current spread is greater then the weapons max spread, set it to max
    41.             if (spread >= maxSpread)
    42.             {
    43.                 spread = maxSpread;
    44.             }
    45.  
    46.             // if the spread is not currently decreasing, start it up cause we just fired
    47.             if (!spreadDecreasing)
    48.             {
    49.                 InvokeRepeating("DecreaseSpread", spreadDecreaseTicker, spreadDecreaseTicker);
    50.                 spreadDecreasing = true;
    51.             }
    52.  
    53.             // if this gun doesn't have infinite ammo, subtract a round from our clip
    54.             if (!infinteAmmo)
    55.             {
    56.                 roundsLeft--;
    57.  
    58.                 // if our clip is empty, start to reload
    59.                 if (roundsLeft <= 0)
    60.                 {
    61.                     StartCoroutine(Reload());
    62.                 }
    63.             }
    64.         }
    65.     }
    66.    
    67. }
    68.  
    69.  
    Gun_BurstFire.cs (anything that fires multiple shots per triggerpull)
    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4. using System.Collections.Generic;
    5.  
    6. /// <summary>
    7. /// component 'Gun_BurstFire'
    8. /// ADD COMPONENT DESCRIPTION HERE
    9. /// </summary>
    10. [AddComponentMenu("Scripts/Gun_BurstFire")]
    11. public class Gun_BurstFire : Gun_Physical
    12. {
    13.     public int burstCount = 3;
    14.     public float burstLag = 0.1f;
    15.  
    16.  
    17.     public override void Fire()
    18.     {
    19.         if (nextFireTime < Time.time)
    20.         {
    21.             StartCoroutine(BurstFire());
    22.            
    23.             nextFireTime = Time.time + fireRate;
    24.         }
    25.     }
    26.  
    27.     IEnumerator BurstFire()
    28.     {
    29.         for (int i = 1; i <= burstCount; i++)
    30.         {
    31.             FireOneShot();
    32.  
    33.             yield return new WaitForSeconds(burstLag);
    34.         }
    35.  
    36.     }
    37.  
    38.  
    39. }
    40.  
    41.  
    Gun_SingleShot.cs
    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5.  
    6. public class Gun_SingleShot : Gun_Physical
    7. {
    8.     public override void Fire()
    9.     {
    10.         if (nextFireTime < Time.time)
    11.         {
    12.             FireOneShot();
    13.  
    14.             nextFireTime = Time.time + fireRate;
    15.         }
    16.     }  
    17. }
    18.  
    Gun_Shotgun.cs
    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5. /// <summary>
    6. /// component 'Shotgun'
    7. /// ADD COMPONENT DESCRIPTION HERE
    8. /// </summary>
    9. [AddComponentMenu("Scripts/Shotgun")]
    10. public class Gun_Shotgun : Gun_Physical
    11. {
    12.     public int pelletCount = 8;
    13.  
    14.    
    15.     public override void Fire()
    16.     {
    17.         if (nextFireTime < Time.time)
    18.         {
    19.  
    20.             for (int i = 0; i <= pelletCount; i++)
    21.             {
    22.                 FireOneShot();
    23.             }
    24.  
    25.             nextFireTime = Time.time + fireRate;
    26.         }
    27.     }
    28.  
    29.  
    30. }
    31.  
    32.  

    Projectile.cs (base projectile for all others to inherit from)
    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4. using System.Collections.Generic;
    5.  
    6. /// <summary>
    7. ///  Base Class for projectiles, contains common elements to all type of projectiles for other projectile  classes to be derived from.
    8. /// </summary>
    9.  
    10. public class Projectile : MonoBehaviour {
    11.  
    12.     protected ProjectileInfo myInfo = new ProjectileInfo();
    13.     protected Vector3 velocity;
    14.     protected int hitCount = 0;
    15.     protected List<Collider> collidersToIgnore = new List<Collider>();
    16.     protected List<Collider> backCollidersToIgnore = new List<Collider>();
    17.        
    18.      
    19.     // This is bullet initialization, It gets called by the weapon that fired this projectile
    20.     public virtual void SetUp(ProjectileInfo info)
    21.     {
    22.         myInfo = info;      
    23.         hitCount = 0;
    24.         velocity = myInfo.speed * transform.forward + transform.TransformDirection(Random.Range(-myInfo.maxSpread, myInfo.maxSpread) * myInfo.spread, Random.Range(-myInfo.maxSpread, myInfo.maxSpread) * myInfo.spread, 1);
    25.         collidersToIgnore.Add (myInfo.owner.GetComponent<Collider>());
    26.         backCollidersToIgnore.Add (myInfo.owner.GetComponent<Collider>());
    27.         Invoke("Recycle", myInfo.projectileLifeTime); // set a life time for this projectile
    28.     }
    29.  
    30.     protected virtual void MakeAHole(RaycastHit hit)
    31.     {      
    32.         foreach (Collider c in collidersToIgnore)
    33.         {
    34.             if (hit.collider == c)
    35.             {
    36.                 return;
    37.             }
    38.         }
    39.  
    40.         BulletHoleManager.bulletHole.SpawnHole(hit);
    41.         collidersToIgnore.Add(hit.collider);
    42.     }
    43.  
    44.     protected virtual void MakeABackHole(RaycastHit hit)
    45.     {
    46.         foreach (Collider c in backCollidersToIgnore)
    47.         {
    48.             if (hit.collider == c)
    49.             {
    50.                 return;
    51.             }
    52.         }
    53.  
    54.         BulletHoleManager.bulletHole.SpawnHole(hit);
    55.         backCollidersToIgnore.Add(hit.collider);
    56.     }
    57.    
    58.     protected virtual void Recycle()
    59.     {
    60.         //Clear the colliders this bullet ignores
    61.         collidersToIgnore.Clear ();
    62.         backCollidersToIgnore.Clear ();
    63.  
    64.         // pool or destroy the bullet when it is no longer used.
    65.         if (myInfo.usePool)
    66.         {
    67.             ObjectPool.pool.PoolObject(gameObject);
    68.         }
    69.         else
    70.         {
    71.             Destroy(gameObject);
    72.         }
    73.     }
    74. }
    75.  
    76.  
    77.  
    78. [System.Serializable]
    79. public class ProjectileInfo
    80. {
    81.     public GameObject owner;
    82.     public string name;
    83.     public Damage damage = new Damage();
    84.     public float force;
    85.     public int maxPenetration;
    86.     public float maxSpread;
    87.     public float spread;
    88.     public float speed;
    89.     public bool usePool;
    90.     public float projectileLifeTime;
    91. }
    92.  
    93.  
    RigidProjectile.cs (projectile based on a rigidbody... cause bullet drop is all the rage)
    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5. public class RigidProjectile : Projectile
    6. {    
    7.     private Rigidbody myRigid;  
    8.  
    9.     public override void SetUp(ProjectileInfo info)
    10.     {
    11.         base.SetUp(info);
    12.         myRigid = GetComponent<Rigidbody>();      
    13.         myRigid.velocity = velocity;
    14.     }
    15.  
    16.     void FixedUpdate()
    17.     {
    18.        // Debug.DrawLine(transform.position, transform.position + myRigid.velocity / 60, Color.red);
    19.        // Debug.DrawLine(transform.position, transform.position - myRigid.velocity / 30, Color.magenta);
    20.  
    21.         RaycastHit hit;  // forward hit
    22.         RaycastHit hit2; // rear hit        
    23.        
    24.         if (Physics.Raycast(transform.position, myRigid.velocity, out hit, (myRigid.velocity.magnitude/Time.deltaTime), ~LayerMask.NameToLayer("Projectiles")))
    25.         {
    26.             // probably shouldn't do this but best way i can think of to avoid
    27.             // multiple hits from same bullet
    28.             //myRigid.MovePosition(hit.point); // move the bullet to the impact point
    29.             transform.position = hit.point;
    30.            
    31.             if (hit.transform.CompareTag("Ground"))
    32.             {// if we hit dirt... kill the bullet since most weapons don't pierce the earth
    33.                 CancelInvoke("Recycle");
    34.                 Recycle();
    35.             }
    36.  
    37.             Health hitObject = hit.transform.GetComponent<Health>();
    38.  
    39.             if (hitObject)
    40.             {                
    41.                 hitObject.Hit(myInfo); // send bullet info to hit object's health component
    42.             }
    43.             else
    44.             {
    45.                 MakeAHole(hit); // make a hole anywhere except the players
    46.             }
    47.    
    48.             hitCount++; // add a hit
    49.  
    50.             if (hitCount > myInfo.maxPenetration)
    51.             {
    52.                 CancelInvoke("Recycle");
    53.                 Recycle(); // if hit count exceeds max hits.... kill the bullet
    54.             }
    55.         }
    56.  
    57.         // this shoots a ray out behind the bullet.
    58.         // use this to add a bullet hole to the back side of a penetrated wall or whatever
    59.         if (Physics.Raycast(transform.position, -myRigid.velocity, out hit2, 2+(myRigid.velocity.magnitude/Time.deltaTime) , ~LayerMask.NameToLayer("Projectiles")))
    60.             {
    61.                 if (hit2.transform.CompareTag("Player"))
    62.                 {
    63.                     // do nothing since we probably already penetrated the player
    64.                 }
    65.                 else
    66.                 {
    67.                     MakeABackHole(hit2);
    68.                 }                
    69.             }
    70.     }  
    71. }
    72.  
    73.  
    That's it for the main scripts (there are a few others in the download).


    Link to Direct Downloads of everything:

    Unity Package File: https://dl.dropboxusercontent.com/u/1475775/CoD/newer/08-07-2015/Novashot_Guns_08072015.unitypackage

    Scripts Only Folder: https://dl.dropboxusercontent.com/u...7-2015/Novashot_Guns_ScriptsOnly_08072015.zip

    Entire Project folder: https://dl.dropboxusercontent.com/u/1475775/CoD/newer/08-07-2015/Novashot_Guns_Project_08072015.zip



    ....Just noticed... as a bonus apparently since I've already typed this up and linked everything... you get my Health script also.


    The original stuff is still below if need be.



    Have fun.
















    Highlights:
    - Multiple Guns in one script
    - Tracers
    - Bullet Penetration
    - bullet randomness, increases over time
    - multiple material ready, just needs effects
    - Look down sights ready
    - Easy


    Here's a gun script that I been working on and it does just about everything. I searched for good gun scripts everywhere and got sick of the search; here is a bit of almost every script I seen all added together. It's a machine gun, burst / single shot, shotgun, and a grenade/rocket launcher all-in one script (c# only sorry). With a few changes in variables, you can make almost any weapon you wish.

    This gun side script supports variable bullet penetration, bullet creates impact effects and bullet holes on both sides of a penetrated wall, and variable tracers. Gun also has variables for random bullet spread with support for a decrease in accuracy during sustained fire from machine guns.

    Burst mode can fire any number of rounds per trigger pull and you can set the time between the rounds fired in the burst. Want a single shot? Set the burst to 1 and done.

    Shotgun has a variable for the number of pellets fired per shot.

    The Launcher supports both rockets and grenades if you're into noob tubes.

    ...the scripts have the framework in for multi-player, but hasn't been fully integrated yet, but should be soon. I'm working with the standard unity master server so my multi-player parts will be geared toward that.

    Forgot to mention, use the right mouse button(fire2) to look down the sights of your gun.

    Here's a Web Player Test of the gun Scripts in action.

    CoD Style Weapons WebPlayer

    Player with guns Unity Package

    If you like what you see, Use and Update these as you see fit. If you happen to add something cool, let everyone else know. Let me know what you think.

    Thanks and have fun.
     

    Attached Files:

    Last edited: Aug 7, 2015
    tlemo_ and chelnok like this.
  2. gamesurgeon

    gamesurgeon

    Joined:
    Oct 11, 2009
    Posts:
    427
    Great! One slight change is that the rockets do not explode after X seconds. By this, I mean if you shoot up, the rocket appears to go on for infinity. Wouldn't be too hard to add a timer code, though.

    Thanks!
     
  3. FreelandCJV

    FreelandCJV

    Joined:
    Nov 12, 2009
    Posts:
    221
    Actually, Alex, you could just make the timer code yourself and add it to the rocket prefab. That way when the rocket spawns the script will count how long until it should destroy the rocket and the rocket's children.
     
  4. GeneralGrant

    GeneralGrant

    Joined:
    Jun 10, 2010
    Posts:
    977
    AMAZING!

    But there is no recoil.
     
  5. novashot

    novashot

    Joined:
    Dec 12, 2009
    Posts:
    373
    Yeah the current rocket just kills itself after so long...without exploding, but that is a simple fix.

    As for the demo, here's the script i used for creating the other weapons and weapon switching.

    I had to add a few lines of code in my gun script to use the weapon switch script, so will attach the updated gun.cs also.

    Thanks for the feed back.
     

    Attached Files:

  6. novashot

    novashot

    Joined:
    Dec 12, 2009
    Posts:
    373

    I did see a gun script with recoil and walk / run sway in. I might update my gun script to have those features soon.
     
  7. GeneralGrant

    GeneralGrant

    Joined:
    Jun 10, 2010
    Posts:
    977
    Wow, pretty impresive. Your first post is a donation of code.

    Pretty awesome.
     
  8. FreelandCJV

    FreelandCJV

    Joined:
    Nov 12, 2009
    Posts:
    221
    Big time donation! I love them! I was working on some scripts like these, but since you made these you saved me a lot of time!

    Thanks so much! :D
     
  9. novashot

    novashot

    Joined:
    Dec 12, 2009
    Posts:
    373
    I updated the gun script a bit to add the ability to choose if you want to run with ray cast bullets or physical bullets. Ray casts are less likely to have "bullet lag" in a multiplayer setting so figured adding the ability was worth while. Also some minor tweaks to the projectile scripts.

    I'm going to add in a multiplayer section to my project soon ( just using the unity master server ). I'll post that update when it is working.

    Let me know if the scripts help you out... I'd love to hear what type or weapons or how they work in your projects.
     

    Attached Files:

  10. novashot

    novashot

    Joined:
    Dec 12, 2009
    Posts:
    373

    Attached Files:

  11. Newnab

    Newnab

    Joined:
    Oct 25, 2010
    Posts:
    7
    Hi there.

    Loving your work here, but I've got a few issues getting this to work with my existing set up (Making a third person game myself) and I was wondering if you could post a demo project file or just advise me where you applied which scripts? If you could I'd be grateful!

    Thanks.
     
  12. NewOrblivia

    NewOrblivia

    Joined:
    Oct 27, 2010
    Posts:
    13
    Looks great, I started over, just cause my own scripts got so messy. I do however get this error, I'm assuming that is because 'offset' is not a function in 'mouselook', did you add another script or modify the mouselook script?

    "Assets/New Gun Assets/Weapons/Scripts/Gun.cs(557,46): error CS1061: Type `MouseLook' does not contain a definition for `offsetY' and no extension method `offsetY' of type `MouseLook' could be found (are you missing a using directive or an assembly reference?)"
    ----------------------

    NVM, got it solved by adding those vars to MouseLook
     
    Last edited: Nov 16, 2010
  13. novashot

    novashot

    Joined:
    Dec 12, 2009
    Posts:
    373
  14. NewOrblivia

    NewOrblivia

    Joined:
    Oct 27, 2010
    Posts:
    13
    Actually my real problem is doing damage to my enemies,. hmmmm at the moment they are listening for specific bullets from my old weapon scripts, hmmm fail.

    Any ideas to what direction I should be looking at?

    I think my old script was overly complicated: Looked like this:

    function OnCollisionEnter(whatObject:Collision) {
    if (whatObject.transform.name == "bulletHit") {

    wakeUpDistance = Vector3.Distance (targetObj.transform.position, transform.position)+1;
    var contact : ContactPoint = whatObject.contacts[0];
    var rotation = Quaternion.FromToRotation( Vector3.up, contact.normal );

    print(whatObject.transform.GetComponent(Projectile).gunType);

    switch (whatObject.transform.GetComponent(Projectile).gunType) {

    case "Handgun":
    blood.particleEmitter.minEmission =10;
    blood.particleEmitter.maxEmission = 20;
    break;
    case "Rifle":
    blood.particleEmitter.minEmission =20;
    blood.particleEmitter.maxEmission = 25;
    break;
    case "Machine Gun":
    blood.particleEmitter.minEmission =30;
    blood.particleEmitter.maxEmission = 50;
    break;
    case "MP5":
    blood.particleEmitter.minEmission = 30;
    blood.particleEmitter.maxEmission = 50;
    break;
    case "Shotgun":
    blood.particleEmitter.minEmission =200;
    blood.particleEmitter.maxEmission = 300;
    break;
    }

    var zombieBlood : GameObject = Instantiate(blood, contact.point, rotation );

    receiveDamage(whatObject.transform.GetComponent(Projectile).damageAmount);
    //zombieSpeed=zombieSpeed-0.05;

    if (hitPoints<1) {
    dieGently();
    }
    }
    }

    function receiveDamage(howMuch) {
    hitPoints-=howMuch;
    return;
    }

    function dieGently() {
    dead=true;
    this.rigidbody.isKinematic = true;
    Destroy (collider);
    AudioSource.PlayClipAtPoint(clip2, Vector3 (101.162, 0.1, 97.67393));
    var whichDie ="die"+Mathf.Round(Random.Range(1,3));
    animation[whichDie].speed = 5;
    animation.CrossFade(whichDie);
    Destroy(gameObject, 5);
    //~ GameObject.FindWithTag("ZombieText").GetComponent(kills).gameText("zombiesdead");

    }

    function dieHeadshot() {
    dead=true;
    // this.rigidbody.isKinematic = true;
    Destroy (rigidbody);
    Destroy (collider);
    AudioSource.PlayClipAtPoint(clip3, Vector3 (101.162, 0.1, 97.67393));
    var whichDie ="die"+Mathf.Round(Random.Range(1,3));
    animation[whichDie].speed = 5;
    animation.CrossFade(whichDie);
    Destroy(gameObject, 5);
    //~ GameObject.FindWithTag("ZombieText").GetComponent(kills).gameText("zombiesdead");
    }
     
  15. novashot

    novashot

    Joined:
    Dec 12, 2009
    Posts:
    373
    My script treats all bullets about the same no matter of what kind of gun that shot them... except the gun script gives the bullets different properties like damage and velocity. I see your current script uses a different impact emitter depending on the type of gun. It would be an easy enough mod to my code to have the bullets know what type of gun fired it. Each bullet fired by my gun is sent and array of information giving the bullet it's specific propeties:

    Code (csharp):
    1.  
    2.         bulletInfo[0] = damage;
    3.         bulletInfo[1] = impactForce;
    4.         bulletInfo[2] = maxPenetration;
    5.         bulletInfo[3] = maxSpread;
    6.         bulletInfo[4] = spread;
    7.         bulletInfo[5] = bulletSpeed;
    8.  
    9.         newBullet.SendMessageUpwards("SetUp", bulletInfo); // send the gun's info to the bullet
    10.  
    You could just as easy add to the array sending the weapon type. You could change the whole array to strings if it would be easier, but then you would need to reconvert the string to a float or int to use it to cause damage. To cause damage my bullet script calls this:

    Code (csharp):
    1.  
    2.             // send a message to the hit object... let it know it was hit
    3.             bulletInfo[0] = ownersName;        // tell hit object who hit them
    4.             bulletInfo[1] = damage.ToString(); // tell them how much damage they recieved
    5.             // send the message
    6.             hit.collider.SendMessageUpwards("ImHit", bulletInfo, SendMessageOptions.DontRequireReceiver);
    7.  
    This sends a string array to the hit object telling the hit object who hit it and how hard. Each player or AI then has the function "ImHit" attached that will break up the array and use the info:

    Code (csharp):
    1.  
    2. public void ImHit(string[] info)
    3.     {
    4.        
    5.         if(!dead)
    6.         {
    7.             string myKiller = info[0];
    8.             float damage = float.Parse(info[1]);
    9.            
    10.             //Debug.Log(" I been hit by " + myKiller + " for " + damage + " damage");          
    11.            
    12.             health -= damage; // do some damage
    13.            
    14.             //Debug.Log("My health is now " + health + " / " + maxHealth);
    15.            
    16.             if(health<=0)
    17.             {  
    18.                             health = 0;
    19.                 dead = true;
    20.                 StartCoroutine(Die());
    21.             }
    22.         }
    23.     }
    24.  
    ImHit takse the bullet info and uses it to damage the player. This array is also very easy to add to if you want to send more information to the target about what hit it. In my function it just subtracts health and if health hits 0 it calls my die function.

    In your case, i would replace your recieveDamage with something similar to my ImHit and then use it to call your deaths. Your impact effects will be trickier because in my scripts the bullet creates the impact effect, not the hit object. You can modify the code to send the gun types and check what it hits to make the same effects though.

    Hope this helps
     
  16. NewOrblivia

    NewOrblivia

    Joined:
    Oct 27, 2010
    Posts:
    13
    Awesome, thx for response, will apply and post it here when its working properly.
     
  17. GrimWare

    GrimWare

    Joined:
    Jul 23, 2009
    Posts:
    211
    The third person view needs some work. Allow the player to aim with the mouse, not just the A and D buttons :)
     
  18. novashot

    novashot

    Joined:
    Dec 12, 2009
    Posts:
    373
    Check the Web player again... I believe you will find some mouse aiming is in for 3rd person now. It's still not pretty, but that construction worker was never meant to carry that weapon anyway :p the project link should be updated as well.

    CoD Style Weapons WebPlayer

    Player with guns Unity Package
     
    Last edited: Feb 27, 2011
  19. goma

    goma

    Joined:
    Dec 17, 2010
    Posts:
    1
    bro....

    can u write a single script
    only for shotgun.....

    i learn fps tutorial, from unity tutorial....
    i have made machinegun, and rocket launcher...
    and i want to make new weapon like your "shotgun".....

    pls help......:p:p
    thx before....... :razz::razz:
     
  20. joeybubble1

    joeybubble1

    Joined:
    Oct 30, 2010
    Posts:
    15
    with the bullet script, how would i make the particle change depending on wot it hits, its cos the case "ground" thing in it already but i tried everthing i know to make it work but it doesnt!!
     
  21. sxg5

    sxg5

    Joined:
    Jan 26, 2011
    Posts:
    2
    Ok, i tried adding this script to a first-person controller, but there's an error in the Gun script dealing with the offsetY: "...does not contain a definition for 'offsetY' and no extension method 'offsetY' of type 'MouseLook' could be found..." How would i fix this??
     
  22. boomcrash

    boomcrash

    Joined:
    Aug 31, 2010
    Posts:
    72
    I'm getting the same error. It needs an FPS character and camera in the scene that have the mouse look script applied,but so far I'm not having much luck getting it to work.
     
  23. sxg5

    sxg5

    Joined:
    Jan 26, 2011
    Posts:
    2
    FPS character is the first-person controller, right?
     
  24. boomcrash

    boomcrash

    Joined:
    Aug 31, 2010
    Posts:
    72
  25. iMAXx

    iMAXx

    Joined:
    Aug 17, 2011
    Posts:
    1
    HI. But can you explain to me what steps to attach?
    Or give please the stage with this project.
     
  26. Z0mbi3Sl43R

    Z0mbi3Sl43R

    Joined:
    Mar 7, 2012
    Posts:
    1
    Thanks for the awsome stuff novashot. I have a problem every tim i start up unity i get this error: Assets/Weapons/Scripts/Gun.cs(206,50): error CS1061: Type `MouseLook' does not contain a definition for `offsetY' and no extension method `offsetY' of type `MouseLook' could be found (are you missing a using directive or an assembly reference?)

    Can ya help me imma noob. thnx
     
  27. Ronkhmps

    Ronkhmps

    Joined:
    Oct 14, 2009
    Posts:
    30
    I am getting this error:

    The type or namespace name `DecalMode' could not be found. Are you missing a using directive or an assembly reference?

    just imported the package and there was the error
    anyone has any idea why?
     
  28. kingcharizard

    kingcharizard

    Joined:
    Jun 30, 2011
    Posts:
    1,137
    This isn't bad but it sill needs much work... I may work on making a fps framework
     
  29. eho

    eho

    Joined:
    Jan 16, 2012
    Posts:
    1
    Thank's for exelent scripts!
     
  30. slasherxtrem

    slasherxtrem

    Joined:
    Aug 8, 2012
    Posts:
    1
    i'm having the same problem, if some one could shed some light on this for me, i would be appreciative
     
  31. roger0

    roger0

    Joined:
    Feb 3, 2012
    Posts:
    1,208
    I'm bumping this thread up in hopes the author may notice. I'm getting the same errors as well. Also, what are the terms of the package? Can we use it on commercial projects?


     
  32. novashot

    novashot

    Joined:
    Dec 12, 2009
    Posts:
    373
    I'll take a look at it tomorrow... at the time I was making those I believe I was playing with the unity decal system in the soldier demo. I probably had some code in my project linked to that for my test but it wasn't working right so I thought I got rid of it. Decals would be used for bullet holes so look there to fix the error, remove anything referring to a decal and just spawn a plane with a bullet hole texture.

    I'll look it over and rewrite or fix it and repost. Sorry I been away so long and threads just seem to get buried pretty fast.

    Use it however you want... it would be cool if you drop me a line letting me know if you do anything cool with it but it's not required.
     
  33. roger0

    roger0

    Joined:
    Feb 3, 2012
    Posts:
    1,208
    Thanks for the quick response! It looks like no one has heard from you for 2 years on this thread. I like the package so far though. I just had to delete the decal script to get it to work. it appears google ranks this first for ''unity 3d weapon script'' and 'unity 3d gun script'. so congrats on that.
     
  34. novashot

    novashot

    Joined:
    Dec 12, 2009
    Posts:
    373
    I'll have to go back and rewrite this at some point here, but use the links in the first post since they were the most up to date links. The first post links don't have the phantom decal stuff in them and on import for me have no errors and compile / play fine on a blank new unity project. set the gun to physical bullets for best results... the raycast bullets require more work to get set up where as physical bullets is pretty much drag and drop.

    To add to a fps controller... have an fps controller in the scene. Drop in a gun prefab. Align the gun prefab to look correct... or how you want it to look in your fps view and make the gun prefab a child of the fps controller's camera. If you drop in the gun prefab, align to camera, parent it, set bullets to physical, and set the fps camera to the gun script's main camera... hit play and it will work.

    I agree it needs more work... i wrote it a few years ago and I need to overhaul it.... kids and life kinda set me back a bit but since there's still an interest in some Call of Duty style weapons I'll try to get back on it asap.... probably merge it with my borderlands style weapons and damage text fountain.

    Sorry again for delay.
     
  35. mujee

    mujee

    Joined:
    Mar 9, 2012
    Posts:
    54


    project folder link is dead please reuploaded
     
  36. iTz DiaMonD iTz

    iTz DiaMonD iTz

    Joined:
    Jan 17, 2013
    Posts:
    4
    Hey, i'm noob on Unity, how i install it? =S
     
  37. Kastar-Troy

    Kastar-Troy

    Joined:
    Jul 18, 2012
    Posts:
    29
    Dude you can't ask beginner questions on something like a complex gun script thread, go through the unity tutorials first, they're awesome and it's the only way to learn properly.

    Nice script btw, gw.
     
  38. roger0

    roger0

    Joined:
    Feb 3, 2012
    Posts:
    1,208
    Hey, I'm trying to use the bullet prefab as the projectile for the UltimateFPSCamera setup. However, once the bullet is instantiated, sometimes it runs into the player and instantiates a hit effect. I tried putting the Character controller on the physics ignore raycast layer but with no luck. Can I get some help?
     
  39. venombreather

    venombreather

    Joined:
    Feb 6, 2013
    Posts:
    1
    how did you fix it? plz help
     
  40. programmer123

    programmer123

    Joined:
    Mar 3, 2013
    Posts:
    2
    Got a question, where do i insert the switch weapons script?? Im new to this so please help.
     
  41. Psycho8Vegemite

    Psycho8Vegemite

    Joined:
    Mar 9, 2013
    Posts:
    8
    pretty simple to add animation using function update with java you could say that when the certain gun is selected and Fire1 is pressed play animation "GunRecoil" and make your animation for the gun. and if you want add a shell projectile and that. you can go far with animations
     
  42. eeveelution8

    eeveelution8

    Joined:
    Feb 16, 2013
    Posts:
    8
    in the directory, Assets/Standard Assets/Decal System/Decal, it whines at me about the following errors :(

    (72,16) the type namespace 'Decalmode' could not be found. are you missing a using directive or assembly reference?
    (75,22) the type namespace 'DecalPolygon' could not be found. are you missing a using directive or assembly reference?
    (76,22) the type namespace 'DecalPolygon' could not be found. are you missing a using directive or assembly reference?
    (114,22) the type namespace 'Meshcombineutility' could not be found. are you missing a using directive or assembly reference?
     
  43. kookabara

    kookabara

    Joined:
    Jun 13, 2013
    Posts:
    7
    ive seen and get this throwback script and its really good one otherwise i need to try this on third person controller maybe later on my project so +1 to you and your script.
     
  44. novashot

    novashot

    Joined:
    Dec 12, 2009
    Posts:
    373
    I updated the first post with a bunch of updated and hopefully more efficient scripts.
     
  45. datgamemakerdude

    datgamemakerdude

    Joined:
    Jun 26, 2013
    Posts:
    1
    I got this error for the single shot script: "Assets/Gun.cs(8,26): error CS0115: `Gun_SingleShot.Fire()' is marked as an override but no suitable method found to override"
     
  46. lordrockit

    lordrockit

    Joined:
    Sep 8, 2013
    Posts:
    3
    amazing i got the cod style wepons pack and in minutes i had an amazing gun from my dreams that you soo much
     
  47. Gab Steve

    Gab Steve

    Joined:
    Nov 3, 2012
    Posts:
    33
    HEY thanks a TON for the scripts! I am currently making an fps game....Sorta like zombies or maybe even just like enemy drones vs the player blah blah.... So would it be fine with You if I used ur script? Reason being i might even sell the game....im not sure how much ill get im not even sure if illl get anything but only if its ok with u will i use them, and i will even put Your name in the credits! Again thanks for the scripts!!! Unity needs more people like u. :D
     
  48. Akshay_ROG

    Akshay_ROG

    Joined:
    Sep 13, 2013
    Posts:
    48
    Project file link DEAD!! reupload brother :)

    EDIT: What the...?!
     
    Last edited: Sep 15, 2013
  49. everett24

    everett24

    Joined:
    Jul 3, 2012
    Posts:
    3
    when i downloaded the package, it says DecalMode does not exist, am i missing something?
     
  50. novashot

    novashot

    Joined:
    Dec 12, 2009
    Posts:
    373
    If there is a decal.cs in there delete it as it was never meant to be in there and obviously is missing some other dependant files.