- Home /
Gameobject Array not working properly
I have two arrays. One is an array of Gameobjects(Enemies). The other one is a Transforms array(empty gameobjects). I have a code where i tell the enemies to go to the empty gameobjects position. See code bellow:
for (int i = 0; i < enemies.Length; i++)
{
enemyPos = enemies[i].transform.position;
for(int j = 0; j < playerPoints.Length; j++)
{
distanceBetweenPlayerAndEnemies = Vector3.Distance(playerPoints[j].transform.position, enemyPos);
if (distanceBetweenPlayerAndEnemies < agent.stoppingDistance)
{
enemies[i].transform.position = playerPoints[j].transform.position;
i++;
}
}
}
This works almost right. The problem is that when i run the game no matter how far the enemies are , as soon as 1 enemy is near the agent.StoppingDistance then all of the enemies teleport inside the empry gameobjects, secondly the more enemies i add i get an error message (INDEX WAS OUTSIDE THE BOUNDS OF THE ARRAY). My question is how to make only the enemies who are less that the agent.stoppingDistance to get in the empty gameobjects position and not everyone? I have tried if statements working with the different disstance but it hasnt worked. Thanks.
Answer by Hawaii_Dev · May 31 at 10:22 AM
The outher for loop is already incrementing i by one each time. Remove the i++ inside the code and change that for a break; instead soo the next enemy can be processed. You get a INDEX out of bounds error since you are increasing i by more than one sometimes and since the array is as long as every object the index will be greater than the length of the array.
But when i remove the i++ in the second loop, then all the "enemies" go to the first position of the playerPoints array. Imagine there are 4 empty game objects around the player, thats where the enemies are supposed to go, so when i remove the i++ they all go on one gameobject instead of spreading.Also when i add a lot of enemies, something like 20-30 then they also all go on the same spots they choose like 3 or 4 positions to go to, i also add 20-30 empty gameobjects.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Why this c# program can not to auto die player 1 Answer
Unity5 filled my SSD? 0 Answers