Unity Crashing. Javascript

This code has been the only code ive been changing the past few days, so it must be this script that is causing the crash on play. im guessing it has something to do with the while script? it was working fine untill i changed the position of the if statement if(currentTime >= 4) to inside the while loop (It was right before the while loop before)

var Enemy : GameObject;
var SpawnedUnits : int = 0;
var CanRespawn : boolean = true;
var currenttime : float;
var TotalWaves : int = 5;
var CurrentWave : int =  1;
var UnitsInWave : int = 10;
var SpawnTime : float = 1.5;
function Update () 
{

	currenttime += Time.deltaTime;
	
	if(CurrentWave <= TotalWaves)
	{
	
		
			while(CanRespawn == true && SpawnedUnits <= UnitsInWave)
			{
			
				if(currenttime >= 4)
				{
					Spawn();
	
					if(SpawnedUnits >= UnitsInWave)
					{
						CurrentWave = CurrentWave + 1;
						UnitsInWave++;
						SpawnTime -= 0.2;
						SpawnedUnits = 0;

					}
				
				}
			}
		
	}
	
}

function Spawn()
{
	
	CanRespawn = false;
	yield WaitForSeconds(SpawnTime);
	Instantiate(Enemy,transform.position,transform.rotation);
	CanRespawn = true;
	SpawnedUnits = SpawnedUnits + 1;
	
}

2 Answers

2

The only thing that I can find out is :

SpawnTime -= 0.2;

This implies that SpawnTime can be negative after some time, and then

yield WaitForSeconds(SpawnTime);

won’t like it …

But if the game crashes when i push the play button, it doesnt even run long enough for SpawnTime to become negative

So there should be something else that crashes the game. You should try deactivating one by one your game objects (with the check box on the top left corner in the inspector) to locate what script is wrong, and then edit your question and post the problematic script when you find it.

if i move if(currenttime >= 4) To right before the while statement: while(CanRespawn == true && SpawnedUnits <= UnitsInWave) It works fine. so the problem is there, and i cant find out why. the working script looks like this if(currenttime >= 4) { while(CanRespawn == true && SpawnedUnits <= UnitsInWave) { but thats the problem, i want there to be a pause inbetween each wave.

The While loop never lets the CPU go long enough to get another Update(). You are infinitely looping.

To verify this, if you add an “else { return; }” to the currentTime check, it stops crashing. I am not saying this is the proper way to fix this though.

This is why it worked when the currentTime check is outside the while loop.