# Need help with an algorithm

I’m making a game with massive battles, units that are far from the player are put in an IBS (Imaginary Battle Simulation) that disables most of their functionalities to save up on CPU. All the units are stored in a list and they can’t use collision detection to find enemies around them when in the simulation. The units can only get other unit’s position from the list they are in. How do I efficiently loop through the list of simulated units and for each of them get them to find their closest neighbors in the list in terms of position in the 3D world (Vector3).

I guess you’ll want to start with a custom class to hold your Enemies as well as the position(s).

``````[CreateAssetMenu(fileName = "Enemy Sim Data", menuName = "ScriptableObjects/EnemiesInSimSO", order = 0)]
public class SimEnemiesSO : ScriptableObject
{
public int enemy;
public Vector3[] others;
public Vector3 closest;
}
``````

Add the array to your Enemy Manager

``````        public List<SimEnemiesSO> simEnemiesSO = new List<SimEnemiesSO>();

public void SpawnEnemy()
{
for (int i = 0; i < 1; i++)
{
//instantiate

simEnemiesSO.Add( new SimEnemiesSO(enemy, enemy.name, simEnemiesSO.Count));
}
}
``````

Then divide the points in some update maybe if you know basic math you should be able to do pointAB = pointB - pontA. Use if statements to determine the closest to add to the `simEnemiesSO.closest[ICODE].`

Optimal approach will probably depend on exactly how many units you intend to simulate. There will be a trade off between number of units and the cost of building / updating an efficient representation for finding nearest neighbours. If you have many (perhaps tens of thousands) then something like a kdtree might be a good approach:

Disclaimer: i have not used this code, just an example. Good luck!

Here is a relevant recent thread: Enemy detection system