Gun, if i press "shoot" key during shooting it will shoot again when the animation ends

Title basically, im using “IEnumerator” to make a delay between my shootings (to finish animation), but if i press shoot twice at the same time it will finish the first shoot and then make another.
This how my gun script looks like:

    void Update()
    {
        if (_input.shoot   && !isShooting)
        {
            Shoot();  
           _input.shoot = false;
        }
    }

    void Shoot()
    {
        GameObject bullet = Instantiate(bulletPrefab, bulletPoint.transform.position, transform.rotation);
        bullet.GetComponent<Rigidbody>().AddForce(transform.forward * bulletspeed);
        Destroy(bullet, 2);
        StartCoroutine(StartRecoil());

    }

    IEnumerator StartRecoil()
    {
        isShooting = true;
        gunAnimator.SetBool("GunShoot", true);
        yield return new WaitForSeconds(0.65f);
        gunAnimator.SetBool("GunShoot", false);
        isShooting = false; // Set shooting state to false when recoil is over
    }


}

If you post a code snippet, ALWAYS USE CODE TAGS:

How to use code tags: Using code tags properly

  • Do not TALK about code without posting it.
    - Do NOT post unformatted code.
  • Do NOT retype code. Use copy/paste properly using code tags.
  • Do NOT post screenshots of code.
  • Do NOT post photographs of code.
  • Do NOT attach entire scripts to your post.
  • ONLY post the relevant code, and then refer to it in your discussion.

Whenever you need more information about what your program is doing as well as how and where it is deviating from your expectations, that means it is…

Time to start debugging!

By debugging you can find out exactly what your program is doing so you can fix it.

Here is how you can begin your exciting new debugging adventures:

You must find a way to get the information you need in order to reason about what the problem is.

Once you understand what the problem is, you may begin to reason about a solution to the problem.

What is often happening in these cases is one of the following:

  • the code you think is executing is not actually executing at all
  • the code is executing far EARLIER or LATER than you think
  • the code is executing far LESS OFTEN than you think
  • the code is executing far MORE OFTEN than you think
  • the code is executing on another GameObject than you think it is
  • you’re getting an error or warning and you haven’t noticed it in the console window

To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run? what order does it run in?
  • what are the names of the GameObjects or Components involved?
  • what are the values of the variables involved? Are they initialized? Are the values reasonable?
  • are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

Knowing this information will help you reason about the behavior you are seeing.

You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as Debug.Log("Problem!",this);

If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

You could also just display various important quantities in UI Text elements to watch them change as you play the game.

Visit Google for how to see console output from builds. If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer for iOS: How To - Capturing Device Logs on iOS or this answer for Android: How To - Capturing Device Logs on Android

If you are working in VR, it might be useful to make your on onscreen log output, or integrate one from the asset store, so you can see what is happening as you operate your software.

Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

If your problem is with OnCollision-type functions, print the name of what is passed in!

Here’s an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

If you are looking for how to attach an actual debugger to Unity: Unity - Manual: Debugging C# code in Unity

“When in doubt, print it out!™” - Kurt Dekker (and many others)

Note: the print() function is an alias for Debug.Log() provided by the MonoBehaviour class.

If you learn more by debugging and there is some specific thing that still seems mysterious…

How to report your problem productively in the Unity3D forums:

http://plbm.com/?p=220

This is the bare minimum of information to report:

  • what you want
  • what you tried
  • what you expected to happen
  • what actually happened, log output, variable values, and especially any errors you see
  • links to actual Unity3D documentation you used to cross-check your work (CRITICAL!!!)

The purpose of YOU providing links is to make our job easier, while simultaneously showing us that you actually put effort into the process. If you haven’t put effort into finding the documentation, why should we bother putting effort into replying?

You need to change the logic in another script where _input.shoot = true is assigned. It should be blocked there as well if the previous shot is not yet finished. Show the code that sets _input.shoot to true.
Be careful with very similar names like isShooting and canShoot. It’s very easy to get confused about which flag is responsible for what.

Thank you for the quick response and the tips, it does get confusing!

this is my input code that sets “shoot” to true:

        public void OnShoot (InputValue value)
        {
            shoot = value.isPressed;
        }

it does get set to true each time i press the input (left mouse button)
but i cant quite understand the logic here because “Shoot()” should get called only when both of those conditions are met
“(_input.shoot && !isShooting)”
and is shooting get set to true only after 0.65 seconds.

The problem lies in the fact that your input system is initially built somewhat incorrectly. Which key is pressed or not should only be determined by the input system itself and no one else. Moreover, as I understand it, you have additionally complicated the task by creating a layer or a mediator between the input system and the objects that use its values.

What’s wrong with this? Currently, your ‘shoot’ property is being controlled by the input system (shoot = value.isPressed) and unexpectedly by the player (_input.shoot = false! at line 7)!

You need to change the input logic so that all objects can only retrieve data from the input system, but cannot set values in it at their discretion.

Everything here is logical and works exactly as you described in the code. Let me try to explain what’s happening at the moment:

  • After the if statement is executed, the Shoot() method is called and _input.shoot = false.

  • Shoot() launches some coroutines that last just over half a second.

  • You quickly press the mouse button a second/third time (while the coroutines are still running), thereby setting shoot to true.

  • That is, the first half of the if condition (_input.shoot && !isShooting) is already fulfilled.

  • And the second half of the condition will be fulfilled immediately after the coroutine StartRecoil() finishes, when isShooting = false triggers (line 26).

  • In the very first Update after the end of the StartRecoil() coroutine, all conditions in if (_input.shoot && !isShooting) are valid, which is why the next shot occurs.

2 Likes

I see it now!
Thank you for taking the effort describing the issue in a way that it acutally make sense, it was not a simple task!
If i could ask just one more thing is for a clue that would guide me in the direction on the “right way” or how would you do it? If the issue is even fixable.

The main thing that is bothering me is why in this input script

        public void OnShoot(InputValue value)
        {
            if (value.isPressed)
            {
                shoot = true;
            }

        }

“shoot” get set to “true” forever and wont be “false” after i release the input key?
i even tried to modify my script to look like this to see if it works:

        public void OnShoot(InputValue value)
        {
            if (value.isPressed)
            {
                // Button is pressed
                shoot = true;
            }
            else
            {
                // Button is released
                shoot = false;
            }
        }

Also, if this is because i cant understand the input system correctly please let me know and i will go back to learning!

Again, thank you very much!

As far as I understand, you are using a new (although it’s been a few years) input system. And honestly, I have no idea how it works, and I haven’t had a chance to use it yet. Therefore, I can only suggest some thoughts on how to fix your problem.

Off the top of my head:

If your OnShoot(InputValue value) method is only called when the button is pressed, then you need to make it react to the release of the button as well. Then the method can be shortened to

public void OnShoot(InputValue value)
{
    shoot = value.isPressed;
}

This is how my initial code looked like and sadly it didnt work, when i was debugging “shoot” it kept returning “true” forever no matter what i did.

Thank you again!