- Home /
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[i].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[i].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[i].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[i].transform.position) < threshold)
{
break;
}
//spawnLocation = new Vector3(newPosition.x,playerY+offset.y,0);
//Debug.Log("Creating enemy number4: " );
}
tempGO[i] = Instantiate(enemytype,spawnLocation,Quaternion.identity);
spawnedEnemies.Add(tempGO[i]);
//Debug.Log("how many enemies "+spawnedEnemies.Count);
enemycounter++;
}
}
isSpawning = false;
}
Which line does the null ref error say it's co$$anonymous$$g from? That already narrows down the problem from 100 lines to one...
Load the position of the last spawned object into a variable. $$anonymous$$ake sure that your new random location does not overlap the variable.
Answer by MinsukCha · Jun 10, 2014 at 09:49 AM
You access tempGO[i] 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.
Your answer
Follow this Question
Related Questions
When GameObject is spawned, rotate x 90. 1 Answer
How do you Place/Spawn a GameObject or Prefab in front of Player 2 Answers
Generate random number and set a GameObject active. 1 Answer
Restart this script 3 Answers
Spawn random amount of gameobjects 2 Answers