I’m still relatively new to programming. I’ve only been taught c#, so please keep answers in c#. I’ve already filled the array with FindGameObjectsOfType, and have the distance updating each frame, but I can’t figure out how to keep the array’s organized by indexer AND seeing which enemy is closest at any given time. I’ve seen a way to reorganize the list of floats by smallest to largest, but I was hoping to keep the indexes between my enemy array and my distance list the same so I could activate a boolean on the enemy that marks it as the closest enemy.
My end goal is to have one single enemy on the entire enemy array marked as the closest enemy. My code so far is in my player’s data model:
public EnemyDataModel[] enemys;
public List<float> enemyDistances = new List<float>();
public int index = 0;
void Start()
{
enemys = GameObject.FindObjectsOfType<EnemyDataModel>();
for(int i = 0; i < enemys.Length; i++)
{
enemys_.name = enemys*.name + i.ToString();*_
enemys*.GetComponent().nameIndex = i;*
enemyDistances.Add(Vector3.Distance(transform.position, enemys*.transform.position);*
}
}
void EnemyProximityCheck()
{
if(index < enemys.Length)
{
enemyDistances[index] = Vector3.Distance(transform.position, enemys[index].transform.position);
index++;
}
else
{
index = 0;
}
}
Like I said before, this at least gets an updated distance per frame for each enemy in my array. And enemyDistances[0] belongs to enemys[0] and so on. How can I compare all the distances in the enemyDistances list, and be able to tell which enemy in the enemys array the smallest distance belongs to? I am open to any possible solutions.
I’ve thought about sorting the list from smallest to largest float, but that would mess up the indexer and I wouldn’t be able to tell which enemy has the smallest distance. I so badly want to hard code everything and just manual type in a float variable for each member of the array that I’ll know will be in the array, but I know it’d be better this way in case my level design changes. I’ve also thought of just typing in an if statement for every possible comparison but that seems like an exorbitant amount of code. There’s gotta be a better way. Please help!