Both sides of my IF statement seem to be firing

I have an odd and confusing situation that has arisen. I believe it is linked to the addition of an animation.

in short I have a situation where you can either

generate a new object
OR
fire the game over function

Code is below

if (gameObject == GameObject.FindGameObjectWithTag("BlackBall")) {
		
		 if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began) {
			
			RaycastHit2D hit = Physics2D.Raycast (Camera.main.ScreenToWorldPoint((Input.GetTouch (0).position)), Vector2.zero);
			
			if 	(hit.collider != null && gameObject == GameObject.FindGameObjectWithTag("BlackBall")) {
				
				animator.Play("anim2");
				generateBall();
			} 
			
			} else { Invoke("gameover", timeref);
				Destroy(this.gameObject, timeref);
			}
	}

The problem seems to be if I touch the ball right on the 0.75 second mark (this is ‘timref’) then I get the game over function firing (this presents the text “GAME OVER” on the screen) but I also get a new object being created.

I’m thinking it’s something to do with the extra 0.1 seconds that the animation takes to happen causing some weird glitch, but I can’t figure it out.

Thanks for any input.

The problem seems to be due to your parenthesis and is easy to spot if you fix the white space. With proper spacing, the code looks like

if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began) {             
    RaycastHit2D hit = Physics2D.Raycast (Camera.main.ScreenToWorldPoint((Input.GetTouch (0).position)), Vector2.zero);             
    if(hit.collider != null && gameObject == GameObject.FindGameObjectWithTag("BlackBall")) {                 
        animator.Play("anim2");
        generateBall();
    }              
} 
else { 
    Invoke("gameover", timeref);
    Destroy(this.gameObject, timeref);
}   

While, based on your question you wanted something like

if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began) {             
    RaycastHit2D hit = Physics2D.Raycast (Camera.main.ScreenToWorldPoint((Input.GetTouch (0).position)), Vector2.zero);             
    if(hit.collider != null && gameObject == GameObject.FindGameObjectWithTag("BlackBall")) {                 
        animator.Play("anim2");
        generateBall();
    }    
    else { 
        Invoke("gameover", timeref);
        Destroy(this.gameObject, timeref);
    }          
}

The logic of your code reads that the only way the game over logic would get called is if the Raycast didn’t actually hit anything. So that would be my first place to check.