Unity crashes when using while

Unity crashes when I trigger this part of the script:

function AutoHit (){
	script.canmove = false;
	while(target == null){
		if(Input.GetKey(KeyCode.Mouse0)){
			var hit : RaycastHit;
			var ray : Ray = camera.main.ScreenPointToRay (Input.mousePosition);
			Physics.Raycast(ray, hit);
			ObjectHit = hit.collider.gameObject.tag;
			if (hit.rigidbody != null){
				if (ObjectHit == "Untagged"){
					script.canmove = true;
					break;
				}
				if (ObjectHit == "Enemy");
				target = hit.collider.gameObject;
			}
		}
	}
	Instantiate(FireBallPrefab,transform.position,Quaternion.identity);
}

It’s activated when the “q” button in pressed.
I’ll list the useful local variables here:

var script = gameObject.GetComponent(Movement);
var FireBallPrefab : GameObject;
var target : GameObject;
var ObjectHit : String;

I expect unity is not crashing, but instead Hanging. This may be because your script will execute forever in that loop while target is null.

Target only gets set when ObjectHit = Enemy. Depending on how quickly it takes to hit an enemy it will continue to execute for ever in this script. Now, in addition, your Physics simulator, main game loop, general game progression is paused because your frame does not progress until your loop exits, that’s why unity seems to hang,

Unity doesent crash, you created infinite loop! Your “while” never exits, it just goes on and on and on.

If your AutoHit doesent get target, it will search for it again and again… but nothing in your game really changed (you are searching same data every time!).

How to fix:

Change “while” to “if”. If your AutoHit is suppose to find target every time it is called but it doesent, then something else in your code/game design is not working well.

============= EDIT =============

This is how code works.

Lets say you have:

  1. Statement1
  2. Statement2 <---- this is your while loop
  3. Statement3

When you start this program, first Statement1 will fire, when done statemen2 will execute and at the end statement3. Now if you have an infinite loop, program will just stay at Statement2 as it never finnishes and Statement3 will also never execute, also program stops responding.

Therefore you HAVE to use IF. You need your game to progress!

Lets say you are looking for a mushroom in a forrest by a tree. Also, lets say time stopped. You can look by that tree for 100.000.000.000.000.000 times, if it wasnt there the first time, it wont be there any other time.

How to work around this than? Use unity events. Add your code in functions like Update or FixedUpdate.

var autoHitStarted: bool = false;

function AutoHit (){
  autoHitStarted = true;
}


function Update() {
  if(autoHitStarted) {
    //Find your target
    //if you found target, set autoHitStarted = false;
  }
}