If statement being called twice. Why?

[SOLVED]

Hello all. I am writting a shooting script - in fact it is finished. My game is in 2D from top view perspective.

Whenever the user clicks the screen, I check if she shot an enemy or not. To do that I create a RaycastHit2D and check if it collides with a GameObject under the layer “zombies”. The code looks like this:

Collider2D hit = Physics2D.OverlapPoint (v2TouchedPos);

if (hit.name==firingZoneName) {
    RaycastHit2D spotted = Physics2D.Raycast (this.survivorTransform.position, ...);
    Debug.Log ("hi");
    if (spotted) {
        //Nothing here due to Debugging tasks 
    }
    Debug.Log ("bye");
}

The problem is that whenever I shoot, the console shows the following (see the attached image):

1727475--108954--Captura.PNG

hi, bye, hi, bye.

This code is inside a shoot() function, which is called from inside the Update() function like so:

void Update() {
    if (Input.GetMouseButtonDown(0))
            shoot  (Camera.main.ScreenToWorldPoint(Input.mousePosition), "SurvivorFiringZone", shotMuzzle);
}

And finally this void Update() is inside a Script named “Shoot.cs” (first letter capitalized), which derives from MonoBehaviour and is attached to a non-moving GameObject with a BoxCollider2D.

What is happening?

Thanks

EDIT: I tried changing Input.GetMouseButtonDown(0) to Input.GetMouseButtonUp(0) but the same thing is happening

EDIT2: The problem was that I had two GameObjects one over the other with the same script attached. This caused the script being called twice. Thanks anyway!

Just to be sure you have only one script running… pause the game, right click on the script in the project folder and select “Find References In Scene”. This let visible in the Hierarchy only the objects containing the script.

2 Likes

Wow, so useful! I didn’t know about it, thank you so much!

1 Like