i am trying to check the distance between many enemies ( their spawn position ) as they spawn at random positions.It works, but is obviously extremely very heavy on performance and sometimes Unity even freezes, so i wanted to ask if there is any better solution ( iam sure there is ).
Here is the code:
if(i > 0)
{
for( var a : int = i; a > 0; a--)
{
while(Vector3.Distance(enemiesPosition*, enemiesPosition[a - 1]) < spawnDistance)*
{ SetRandomPosition(); print(“adjusting distance”); } } } I am looping index of an array. EnemiesPosition is Vector3, its position of current enemy and its comparing distance of the previous enemy. If it is in given range, it sets new position. If not it loops again with another enemy which was spawn earlier. I am having like 15 enemies and its totaly crushing Unity, so i guess that the looping for all enemies is the issue, but i dont know how to else check for all other enemies spawning positions so they dont spawn on same spot. Thanks for any reply. Luke
You can span your loop over several frames using yield, which would reduce the load. You could do the following:
private var busy = false; // declare this flag outside any function
...
if(i > 0 && !busy){ // only checkEnemies when last job ended
checkEnemies(i);
i--; // only goes to the next enemy when this one was verified
}
...
function checkEnemies(i: int)
{
busy = true; // I'm busy here
for( var a : int = i; a > 0; a--)
{
while(Vector3.Distance(enemiesPosition*, enemiesPosition[a - 1]) < spawnDistance)*
{ SetRandomPosition(); print(“adjusting distance”); } yield; // continue in next frame } busy = false; // I’m done } The checkEnemies function sweeps the enemies as before, but after checking each enemy it suspends execution with yield, and only resume in the next frame. It sets the variable busy at start to signal it’s working - the caller code must not call this function again until it has finished - and clears it at the end. You must also pass to the next enemy only when checkEnemies has ended - that’s why I placed the i decrement after checkEnemies (I’m supposing you’re sweeping the enemies with variable i from the number of enemies to 0; if not, adapt this code to your logic).