[c#] While loop not exiting, I have no idea why

What I’m trying to do is make sure that there isn’t already a gameObject in the spot I’m trying to spawn my gameObject.

To the best of my knowledge I’ve accounted for all possible outcomes and am also using the raycast correctly.

   public void SpawnAttackShip(){
    		bool spawned = false;
    		while(spawned == false){
    			Vector3 position = new Vector3(Random.Range(screenLeft.x, screenRight.x), screenTop.y, 0);
    			Ray ray = Camera.main.ViewportPointToRay(Camera.main.WorldToViewportPoint(position));
    			RaycastHit hit;
    			if(Physics.Raycast(ray, out hit)){
    				if((hit.transform.tag == "Enemy")){
    					spawned = false;
    				}
    				if((hit.transform.tag == null)){
    					GameObject attackShip = (GameObject)Instantiate(theAttackShip, position, Quaternion.identity);
    					spawned = true;
    
    				}
    			}
    			else{
    				GameObject attackShip = (GameObject)Instantiate(theAttackShip, position, Quaternion.identity);
    				spawned = true;
    
    			}
    		}
    	}

I’ve been trying to troubleshoot it but its tough because it makes unity crash in the infinite loop.

if((hit.transform.tag == null)){

Tag generally never equals null. If you haven’t tagged something it has the tag string “Untagged”.

This is why you’re getting an infinite loop. Neither of your conditions can ever cause spawned to equal true.

Troubleshooting infinite loops is a bit tricky - the best way is often to either open a debugger, or go for the cheap option:

int safety = 0;
while(spawned == false && safety < 100)
    safety++;
    ...
}

Generally, having an while-loop run until some randomly generated value gets a favorable value is not ideal. In your case, it seems that your raycast is always hitting something with the Enemy tag - which might mean that you’ve tagged some background with “Enemy”, or that your rays are not doing what you think they are. A quick solution (that probably should be in anyways) would be to just give up after a bunch of iterations, and try again later.

Also, please, use while(!spawned) instead of while(spawned == false). It reads better - “I want to run the loop while the ship has not spawned” rather than “I want to run the loop while the ship having spawned is false”.