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

C# Gun shooting script

Discussion in 'Scripting' started by chris_gamedev, Jun 1, 2019.

  1. chris_gamedev

    chris_gamedev

    Joined:
    Feb 10, 2018
    Posts:
    34
    I feel a bit dumb for this one because I can't quite get my head around the right logic.
    Code (CSharp):
    1. protected override void HandleInput()
    2. {
    3.     if (Input.GetButtonDown("Fire1"))
    4.     {
    5.         if (ammoClip > 0)
    6.         {
    7.             Shoot();
    8.         }
    9.     }
    10. }
    This works great for semi-automatic/shoot-as-fast-as-you-can-click type shooting.

    Code (CSharp):
    1. protected override void HandleInput()
    2. {
    3.     if (Input.GetButton("Fire1") && Time.time >= nextTimeToFire)
    4.     {
    5.         nextTimeToFire = Time.time + 1f / fireRate;
    6.         if (ammoClip > 0)
    7.         {
    8.             Shoot();
    9.         }
    10.     }
    11. }
    This works great for fully-automatic shooting.

    I don't want there to be a physical switch to activate separate firing modes, but instead I want to be able to hold and
    GetButton("Fire1")
    and it shoot a round every 1 second, but still be able to mash and
    GetButtonDown("Fire1")
    and fire as fast as can be clicked.

    Any rough suggestions on how to form that logic?
     
  2. DonLoquacious

    DonLoquacious

    Joined:
    Feb 24, 2013
    Posts:
    1,667
    Maybe something like this?
    Code (csharp):
    1. protected override void HandleInput()
    2. {
    3.     if (Input.GetButtonDown("Fire1") || (Input.GetButton("Fire1") && Time.time >= nextTimeToFire))
    4.     {
    5.         nextTimeToFire = Time.time + 1f / fireRate;
    6.         if (ammoClip > 0)
    7.             Shoot();
    8.     }
    9. }
     
    chris_gamedev likes this.
  3. chris_gamedev

    chris_gamedev

    Joined:
    Feb 10, 2018
    Posts:
    34
    :rolleyes:

    Thank you. I haven’t actually tested it but you’re bound to be right and I should have figured that one out for myself.