Search Unity

  1. We are migrating the Unity Forums to Unity Discussions. On July 12, the Unity Forums will become read-only.

    Please, do not make any changes to your username or email addresses at id.unity.com during this transition time.

    It's still possible to reply to existing private message conversations during the migration, but any new replies you post will be missing after the main migration is complete. We'll do our best to migrate these messages in a follow-up step.

    On July 15, Unity Discussions will become read-only until July 18, when the new design and the migrated forum contents will go live.


    Read our full announcement for more information and let us know if you have any questions.

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

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

  1. ChandlerVS

    ChandlerVS

    Joined:
    Dec 21, 2013
    Posts:
    2
    I tried to add the Controller script parts to the Mouse Movement Script. I receive this error:

    Assets/Standard Assets/Character Controllers/Sources/Scripts/MouseLook.cs(33,9): error CS0246: The type or namespace name `Gun' could not be found. Are you missing a using directive or an assembly reference?

    Assets/Standard Assets/Character Controllers/Sources/Scripts/MouseLook.cs(34,9): error CS0246: The type or namespace name `WeaponType' could not be found. Are you missing a using directive or an assembly reference?

    I got rid of the weapontype error by typing in Using Gun;
     
    Last edited: Dec 21, 2013
  2. DwcsX

    DwcsX

    Joined:
    Jan 7, 2014
    Posts:
    2

    How did you fix the OffsetY error. I tried adding vars to the 'Mouse Look' script but I am kin of new to C+ and Javascript. can you help me please.

    Thanks
     
  3. z3nth10n

    z3nth10n

    Joined:
    Nov 23, 2013
    Posts:
    65
    Last edited: Jan 7, 2014
  4. DwcsX

    DwcsX

    Joined:
    Jan 7, 2014
    Posts:
    2
    Thanks for the link. It really did the trick.
     
  5. Takahama

    Takahama

    Joined:
    Feb 18, 2014
    Posts:
    169
    Thanks novashot! its an epic script! but.. i have only one question : Where Reload button ? :l "R"
     
  6. novashot

    novashot

    Joined:
    Dec 12, 2009
    Posts:
    373
    Sorry in the latest version of the script I stripped out player input from the weapon so you could theoretically have a single script that handles player input. In your player input script you should already have a reference of the weapon script if you are firing the weapon so just set up a reload button and call the reload function when the button is pressed.

    Pseudo style:
    Code (csharp):
    1.  
    2.  If (input.getbutton("reload")
    3. {
    4.        Myweaponscript.reload ();
    5. }
    6.  
    7.  

    I just find it a pain when player input is scattered in 20 scripts so made this input independent...
     
  7. Takahama

    Takahama

    Joined:
    Feb 18, 2014
    Posts:
    169
    Sorry but.. which one is the lastest version ?
    "novashot_cod_style_weapons_201.unitypackage"
    or
    "Player with guns Unity Package"
    Thanks!
     
  8. Takahama

    Takahama

    Joined:
    Feb 18, 2014
    Posts:
    169
    oh and i do not understand what i do for reload :l
     
  9. Takahama

    Takahama

    Joined:
    Feb 18, 2014
    Posts:
    169
    novashot, please can you write a reload script for us ? Thank you ^^
     
  10. G_Scheffer

    G_Scheffer

    Joined:
    Mar 18, 2014
    Posts:
    3
    Do I have to modify this script if so what do I need because ive got the stock script he linked and It gives me
    Assets/Gun_SingleShot.cs(8,26): error CS0115: `Gun_SingleShot.Fire()' is marked as an override but no suitable method found to override
    how do I fix that
     
  11. novashot

    novashot

    Joined:
    Dec 12, 2009
    Posts:
    373
    Gun_SingleShot.cs is an extension of the Gun.cs.... so you need both in the project. All of the Gun_ are extensions of Gun so throw all of them in the project to get them to work.
     
  12. G_Scheffer

    G_Scheffer

    Joined:
    Mar 18, 2014
    Posts:
    3
    i do but it ssaid that about all of them and I don't know what to do from there and I am a beginner on coding so I don't know on wat needs done to fix
     
  13. G_Scheffer

    G_Scheffer

    Joined:
    Mar 18, 2014
    Posts:
    3
    Is my problem the fact that I downloaded them and didn't add or edit them at all, I just downloaded them and hoped that they worked
     
  14. novashot

    novashot

    Joined:
    Dec 12, 2009
    Posts:
    373
    If you downloaded Novashot_Gun_81313.zip and unzipped it directly into your project... all the files... it does work. I've done it myself just to test... download it into a blank project and there are no errors and I can get a working gun in a minute. But you need all of the files... Yes I know it's a failing on my part because I didn't put it in a unity package and I need to redo it... probably with a scene with an fps player and a working gun on it to show the exact set up. If I can muster the drive to do so... I'll attempt to get such a package up on the front page tonight.... anyway the proper setup is as follows:

    1: Standard FPS Controller
    create an empty game object(this is your gun container-can make any model a child of this for your visible gun)
    make the "gun" object a child of the FPS controller's camera ( this allows it to move as your camera does)
    also position this "gun" object to where your gun would be on your character
    create another empty game object ( this will be your muzzle point...where your bullets are spawned)
    make the "muzzle" object a child of the "gun" object and make sure the "muzzle" object's forward vector
    Position this object relative to the end of your gun barrel(if you have a model) or just in front of your player if no model yet
    make sure the "muzzle" object's forward vector faces away from your character( all bullets will use this vector as a direction they need to travel so if it's not aligned properly bullets will misbehave)

    2: Create a new object( I use a very small sphere) for a bullet object
    Add a rigidbody to the sphere and go ahead and remove the collider from it(my projectile script uses raycasts so the collider is not needed and may cause grief when it does actually collide with something and stop dead in its tracks)

    3. Create a new prefab ( projectile )
    Add the projectile object to the prefab... once the prefab is set up you can delete the projectile object from the scene ( don't delete the prefab)

    4: Download and unzip Novashot_Gun_81313.zip.
    Make sure all of the files are in your project.

    5. Add the projectile script to the projectile prefab

    6. Pick out your favorite Gun_script and add that to your "gun" container object from step 1. (Gun.cs is a base component and shouldn't be added to weapons... use the Gun_ child components)

    7 Setup the gun script
    after adding the script to your gun container object... drag your "muzzle" object onto the gun script's muzzle variable
    drag the projectile prefab to the gun script's projectile variable
    mess with whatever variables you want(damage, spread, velocity...)
    the UseObjectPooling bool...if you take the false route... skip the next step

    8 Object pooling -- creates a pool of frequently used object and recycles them so they aren't created and destroyed alot
    Create an empty object in your scene - name it "Scripts"
    Add the objectPool script to it
    edit the settings... add your projectile prefab to the prefab list
    in the amount list add how many projectiles you want to be pre-setup (make sure the prefab and number are in the same index for the list)

    9 BulletHoleManager.cs.....
    Not sure where I was heading with this but I made the mistake of having it in there so I guess for this example we will have to roll with it.... basically before I had each bullet hole take care of itself... think I was going for a centralized bullet hole system here but never finished it completely
    if (you created the script object above){
    add bullet hole manager script to the scripts object
    } else {
    Create an empty object in your scene ... name it bullethole manager for fun
    Add the bullethole manager script to said object
    }

    10 Player Script....

    Create a new C# script... name it PlayerInput.cs
    open the file and add a few things:

    2 variables

    Code (csharp):
    1.  
    2. // a few variables
    3.     Gun myGun;  // because all gun types are derived from the base gun class, we can cast it as Gun instead of trying to determine the current gun type
    4.     WeaponType myWeaponType; // the current gun's enum weapon type
    5.  
    in the Start() function add the line:

    Code (csharp):
    1.  
    2. GetWeaponScript();
    3.  
    below the start function add a new function:

    Code (csharp):
    1.  
    2. // call this to get the current weapon type, call on pick up, weapon swap... whenever but do it before you can use the gun
    3.     public void GetWeaponScript()
    4.     {
    5.         myGun = GetComponentInChildren<Gun>();
    6.  
    7.         if (myGun) // check if we have a gun script first to avoid errors
    8.         {
    9.             myWeaponType = myGun.typeOfWeapon;
    10.         }
    11.     }
    12.  

    inside of the Update() function add:

    Code (csharp):
    1.  
    2. if (myGun) // check if we have a gun script first to avoid errors
    3.         {
    4.             if (myWeaponType == WeaponType.FULLAUTO)
    5.             {
    6.                 if (Input.GetButton("Fire1"))
    7.                 {
    8.                     myGun.Fire();
    9.                 }
    10.             }
    11.             else
    12.             {
    13.                 if (Input.GetButtonDown("Fire1"))
    14.                 {
    15.                     myGun.Fire();
    16.                 }
    17.             }
    18.  
    19.            if(Input.GetKeyDown(KeyCode.R))
    20.            {
    21.                   myGun.Reload(); ///whoever was asking for a reload function... it was already built in... you just need to call it
    22.            }
    23.         }
    24.  
    Did all of this from memory... not actually near my unity install right now so might have a few errors but this should get you going.

    Hope it helps and I hope I can get around to putting up a package soon.

    Thanks
     
  15. novashot

    novashot

    Joined:
    Dec 12, 2009
    Posts:
    373
    Just so you guys who were asking about stuff in here know... I am currently revisiting these scripts and they did work as they were but I did find a few flaws also so I am reworking parts of them and building a simple scene / unity package to hopefully ease the process. As for the reload as I have it above... it won't work exactly that was due to my Reload function being an IEnumerator type and as such it can't be called that way...it is one of the fixes. Also changed the way it kept track of bullets since the way I had it was down right stupid.

    Either way I didn't forget and didn't mean to leave you fine people with crap code... so a fix should be here some time this weekend.
     
  16. Deleted User

    Deleted User

    Guest

    so how are the new scipts working?
     
    Last edited by a moderator: Apr 15, 2014
  17. dulluncharted

    dulluncharted

    Joined:
    Jan 11, 2014
    Posts:
    2
    just make the animation so the gun lifts up a bit
     
  18. T152

    T152

    Joined:
    Apr 18, 2014
    Posts:
    2
    when ever i try to make my own gun it shoots to the left no matter what i do
     
  19. novashot

    novashot

    Joined:
    Dec 12, 2009
    Posts:
    373
    if it's like mine or based on mine, make sure the muzzle point's forward vector is facing the direction you want to shoot.
     
  20. T152

    T152

    Joined:
    Apr 18, 2014
    Posts:
    2
    nope i using yours and i don't know what a forward vector yet no matter what rotation i use
     
  21. XYZglitch

    XYZglitch

    Joined:
    Jul 10, 2014
    Posts:
    1
    Anyone make a YouTube tutorial on this? Ninja Boy made one but it is a #fail
     
  22. novashot

    novashot

    Joined:
    Dec 12, 2009
    Posts:
    373
    what app do people use to do screen->video for youtube? Setup is pretty basic overall, but I could throw one together if I knew what to use for it.
     
  23. chelnok

    chelnok

    Joined:
    Jul 2, 2012
    Posts:
    680
    @novashot if you using osx, you can use quicktime for screen recording, and iMovie to edit and upload.
     
  24. novashot

    novashot

    Joined:
    Dec 12, 2009
    Posts:
    373
    I'm a pc guy... not that it matters both powered by intel I suppose :p So I guess I'm a Windows guy then.
     
  25. chelnok

    chelnok

    Joined:
    Jul 2, 2012
    Posts:
    680
    I dont know if they are available for windows, probably not. For windows, there is fraps, but i havn't ever used it.
     
  26. bobaustin122227

    bobaustin122227

    Joined:
    Sep 20, 2014
    Posts:
    3
    If you have a problem with "The type or namespace name `DecalMode' could not be found. Are you missing a using directive or an assembly reference?" go to unity and under project Search up simple Assets and inside you will see the file DecalMode delete the file DecalMode.
     
  27. ltwl12

    ltwl12

    Joined:
    Dec 22, 2014
    Posts:
    1
    Ever since I set up the gun script my gun would not scope correctly. When i right click my screen turns the color of my gun. Could it be a problem that I had already created a scope function, and it is not compatible with the gun script you have?
     
  28. novashot

    novashot

    Joined:
    Dec 12, 2009
    Posts:
    373
    Pretty hard to say without seeing your code or what you did.
     
  29. Evolution-Games

    Evolution-Games

    Joined:
    Jan 4, 2015
    Posts:
    1
    after i had put the code on to my gun this message appeared in the error box

    NullReferenceException: Object reference not set to an instance of an object
    Gun+<FireOneShot>c__Iterator1.MoveNext () (at Assets/Assets fps/Fps Shooting/Gun.cs:327)
    UnityEngine.MonoBehaviour:StartCoroutine(String)
    Gun:MachineGun_Fire() (at Assets/Assets fps/Fps Shooting/Gun.cs:207)
    Gun:Update() (at Assets/Assets fps/Fps Shooting/Gun.cs:107)

    what dose this mean
     
  30. DMac360

    DMac360

    Joined:
    Apr 3, 2015
    Posts:
    17
    I'm new to unity; how would I add audio to the gun?
    I also don't quite understand how to add damage to the bullets.
     
  31. DMac360

    DMac360

    Joined:
    Apr 3, 2015
    Posts:
    17
    I'm creating an Enemy AI
    How would I make this so that when the bullet hits the enemy, the Health subtracts the amount of damage for the bullet. I'm using Novashot's gun scripts

    Code (JavaScript):
    1. var Player : Transform;
    2. var MoveSpeed = 4;
    3. var MinDist = 5;
    4. var MaxDist = 10;
    5. var EnemyHealth = 100;
    6.  
    7. function Start() {
    8.  
    9. }
    10.  
    11. function Update() {
    12.     transform.LookAt (Player);
    13.    
    14.     if(EnemyHealth == 0){
    15.         Destroy(this.gameObject);
    16.     }
    17.    
    18.     if(Vector3.Distance(transform.position, Player.position) >= MinDist){
    19.     PlayerHealth -= 20;
    20.     }
    21.    
    22.     if(Vector3.Distance(transform.position, Player.position) >= MinDist) {
    23.        
    24.         transform.position += transform.forward * MoveSpeed * Time.deltaTime;
    25.        
    26.         if (Vector3.Distance(transform.position, Player.position) <= MaxDist){      
    27.         }
    28.     }
    29. }
     
    Last edited: Apr 4, 2015
    KingLlama likes this.
  32. KingLlama

    KingLlama

    Joined:
    Jul 18, 2015
    Posts:
    199
    I literally was just about post this because my enemy health script isn't working correctly at all.

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4.  
    5. public class EnemyHealth : MonoBehaviour {
    6.    
    7.    
    8.     public int maxHealth = 100;
    9.     public int curHealth = 100;
    10.    
    11.     public float healthBarLength;
    12.    
    13.     // Use this for initialization
    14.     void Start () {
    15.         healthBarLength = Screen.width / 2;
    16.     }
    17.    
    18.     // Update is called once per frame
    19.     void Update () {
    20.         AdjustCurrentHealth(0);
    21.     }
    22.    
    23.     void OnGUI() {
    24.        
    25.         GUI.Box (new Rect (10, 40, healthBarLength, 20), curHealth + "/" + maxHealth);
    26.        
    27.        
    28.     }
    29.    
    30.    
    31.     public void AdjustCurrentHealth(int adj) {
    32.         curHealth += adj;
    33.        
    34.         if(curHealth < 0)
    35.             curHealth = 0;
    36.        
    37.         if (curHealth > maxHealth)
    38.             curHealth  = maxHealth;
    39.        
    40.         if (maxHealth < 1)
    41.             maxHealth = 1;  
    42.        
    43.         healthBarLength = (Screen.width / 2) * (curHealth / (float)maxHealth);
    44.        
    45.        
    46.     }
    47. }
     
  33. novashot

    novashot

    Joined:
    Dec 12, 2009
    Posts:
    373
    What isn't working? In update you tell it to adjust itself by 0 every frame. How does your bullet / damage source look?

    personal note: I hate having anything in OnGUI or Update for something like this. Your health only changes when something affects it so update is not required (if you use regen/DoT... use invoke repeating or similar). My health bars were gameobjects with billboarding which were changed if health was altered.

    -- This post was my very first post on the forums so as is....is pretty badly written (also I forget what exactly was in it) I will have to download the package myself and see what was in it but I am pretty sure the bullets in this were rigidbodies that were given a velocity when fired and used a forward raycast to detect hits. You would add a sendmessage or GetComponent<health> call to a hit object and call your damaging function to affect health.
     
  34. KingLlama

    KingLlama

    Joined:
    Jul 18, 2015
    Posts:
    199
    I'm really new to scripting that is why I am using your code you made for us. I'm learning how to read and edit. So would I add sendmessage or get component to my health script or to the gun script?
     
  35. novashot

    novashot

    Joined:
    Dec 12, 2009
    Posts:
    373
    I just downloaded my scripts again to take a peek. in Bullet.cs OnHit function about line 175 there is this line:

    Code (csharp):
    1.  
    2.         hit.collider.SendMessageUpwards("ImHit", bulletInfo, SendMessageOptions.DontRequireReceiver);
    3.  
    This already sends the message "ImHit" to whatever object the bullet hits with that bullet's info (including damage). You would either change the function in your health script from "AdjustCurrentHealth" to "ImHit" or preferably go to line 175 and change "ImHit" to "AdjustCurrentHealth". In your case, also on line 175, change "bulletInfo" to "damage" since your function only cares for the damage part(also you would get an error since your function expects an int and would get a List<projectile>.

    Code (csharp):
    1.  
    2.         hit.collider.SendMessageUpwards("AdjustCurrentHealth", damage, SendMessageOptions.DontRequireReceiver);
    3.  
    On another note after looking at this... I would go and change damage, maxHits and speed from floats to ints (damage for sure or you will need to cast it to int in the example above)... I was pretty bad when I wrote this... but there wasn't much out there like it back then. I think I have an update somewhere if the world has interest in a weapon system like this still.
     
    KingLlama likes this.
  36. KingLlama

    KingLlama

    Joined:
    Jul 18, 2015
    Posts:
    199
    The world still has a interest... I just ran into in this problem

    "MissingMethodException: The best match for method AdjustCurrentHealth has some invalid parameter.
    System.MonoType.InvokeMember (System.String name, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object target, System.Object[] args, System.Reflection.ParameterModifier[] modifiers, System.Globalization.CultureInfo culture, System.String[] namedParameters) (at /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System/MonoType.cs:520)
    UnityEngine.SetupCoroutine.InvokeMember (System.Object behaviour, System.String name, System.Object variable) (at C:/buildslave/unity/build/Runtime/Export/Coroutines.cs:18)
    UnityEngine.Component:SendMessageUpwards(String, Object, SendMessageOptions)
    Bullet:OnHit(RaycastHit) (at Assets/Weapons/Scripts/Bullet.cs:183)
    Bullet:Update() (at Assets/Weapons/Scripts/Bullet.cs:103)"
     
  37. novashot

    novashot

    Joined:
    Dec 12, 2009
    Posts:
    373
    Your AdjustCurrentHealth function expects an int as input... my bullet script there stores damage as a float. either go through the bullet script and convert it to an int or cast it as an int before sending it off to adjust health.

    like
    Code (csharp):
    1.  
    2. hit.collider.SendMessageUpwards("AdjustCurrentHealth", (int)damage, SendMessageOptions.DontRequireReceiver);
    3.  
     
  38. hattyh

    hattyh

    Joined:
    Jul 8, 2015
    Posts:
    15
    Awesome script i love it, but the auto reload is setting me back a bit, i wanna have it to reload when pressing "r", ive tried almost everything :|
     
  39. phoda

    phoda

    Joined:
    Nov 11, 2014
    Posts:
    384
    Code (CSharp):
    1. if (Input.GetButtonDown(KeyCode.R))
    2.         {
    3.             StartCoroutine("reload");
    4.         }
    just add that to update function below fire2
     
  40. hattyh

    hattyh

    Joined:
    Jul 8, 2015
    Posts:
    15
    Where excactly? :|
     
  41. phoda

    phoda

    Joined:
    Nov 11, 2014
    Posts:
    384
    In gun script find fire 2 and move to end of that if statment then just copy my part
     
  42. novashot

    novashot

    Joined:
    Dec 12, 2009
    Posts:
    373
    That will do it.... I really need to post newer stuff if people are still using this old gun script
     
  43. phoda

    phoda

    Joined:
    Nov 11, 2014
    Posts:
    384
    I didnt use the script but nice contribution to community, i just peeked into it but nice
     
  44. novashot

    novashot

    Joined:
    Dec 12, 2009
    Posts:
    373
    Good news... I updated the original post with new stuff. Didn't realize I had in on this PC... but I did so there we go.
     
    KingLlama likes this.
  45. Ghost004

    Ghost004

    Joined:
    Jan 27, 2016
    Posts:
    3
  46. Ghost004

    Ghost004

    Joined:
    Jan 27, 2016
    Posts:
    3
    So sooner or later on full auto the bullets start spawning out of hit point and not the muzzle
    also reload is not taking ammo reserve bullets
    any who stuff i noticed with new scripts

    I keep using these over the years so thanks again
     
  47. xCMurder

    xCMurder

    Joined:
    Aug 2, 2015
    Posts:
    1
    Honestly I tried placing these scripts in my game but still have no idea how to get this to work. Can Someone please help me?
     
  48. HittmanA

    HittmanA

    Joined:
    Jul 27, 2016
    Posts:
    45
    Is there a 5.0 version of this?
     
  49. novashot

    novashot

    Joined:
    Dec 12, 2009
    Posts:
    373
    I thought I tried this in 5... was there something that you found that didn't work? I haven't worked on this in quite a while but I can take a peek if something is not working.
     
  50. Unityolks

    Unityolks

    Joined:
    Jul 1, 2017
    Posts:
    3
    thank God for novashot, you really helped me a lot