Stop object spawning on top of each other?

i have this function that spawns enemies in random positions i noticed that they sometimes spawn on top of each other so i tried to use vector2.distance, to compare the old enemy position by the new enemy position but it wont work come up with a error telling me my script is trying to access a object with null this is the code.

function spawnenemytype (enemytype:GameObject, amount:int)

{

var spawnLocation:Vector3;

var temp:int;
isSpawning = true;
var pos:Vector2 = Vector2.zero;

for (var k:int = 0; k < 1000; k++)
{
		var randomX:float = Random.Range(minX, maxX);
		var randomY:float = Random.Range(minY, maxY);
        pos = new Vector2(randomX, randomY);
        
for ( var i:int = 0; i < amount; i++)
{
	yield WaitForSeconds(1);
 
	temp = Random.Range(1,5);

	if (temp == 1)
	{	
		if (spawnedEnemies.Count == 0)
		{
			spawnLocation = new Vector3(pos.x,playerY + offset.y,0);
		}
		else if (Vector2.Distance(spawnLocation , tempGO*.transform.position) < threshold)*
  •  {	*
    
  •  	break;*
    
  •  }*
    
  • }*

  • if (temp == 2)*

  • {*

  •  if (spawnedEnemies.Count == 0)*
    
  •  {*
    
  •  	spawnLocation = new Vector3(pos.x,playerY + offset.y,0);*
    
  •  }*
    

_ else if (Vector2.Distance(spawnLocation , tempGO*.transform.position) < threshold)_
_
{ _
_
break;_
_
}*_

* }*

* if (temp == 3)*
* { *

* if (spawnedEnemies.Count == 0)*
* {*
* spawnLocation = new Vector3(pos.x,playerY + offset.y,0);*
* }*
_ else if (Vector2.Distance(spawnLocation , tempGO*.transform.position) < threshold)
{
break;
}*_

* }*

* if (temp == 4)*
* {*

* if (spawnedEnemies.Count == 0)*
* {*
* spawnLocation = new Vector3(pos.x,playerY + offset.y,0);*
* }*
_ else if (Vector2.Distance(spawnLocation , tempGO*.transform.position) < threshold)
{
break;
}
//spawnLocation = new Vector3(newPosition.x,playerY+offset.y,0);
//Debug.Log("Creating enemy number4: " );*_

* }*

tempGO = Instantiate(enemytype,spawnLocation,Quaternion.identity);
spawnedEnemies.Add(tempGO*);*

//Debug.Log("how many enemies "+spawnedEnemies.Count);
enemycounter++;

}
}

isSpawning = false;

}

You access tempGO before it is instantiated. For example, if i = 1 in your for loop, then tempGO[1] is null but it can be accessed when you check Vector2.Distance. When i =1, Only tempGO[0] is instantiated.