- Home /
Prioritizing objects in an array based on a variable value?
Hey all, I'm working on a targeting system for some turrets in my game. What I have at moment works fine for the majority of my turrets. It returns a target based on the closest enemy. What I need is a way to prioritize certain enemies to be targeted before the others, unless no priority targets are available in which case to simply target the closest.
Here's my targeting code at the moment.
public Transform target;
public Transform closestenemy;
public GameObject[] enemies;
public Transform getClosestenemy()
{
enemies = GameObject.FindGameObjectsWithTag("enemy");
float closestenemy = Mathf.Infinity;
Transform trans = null;
foreach (GameObject go in enemies)
{
float currentenemy;
currentenemy = Vector3.Distance(transform.position, go.transform.position);
if (currentenemy < closestenemy)
{
closestenemy = currentenemy;
trans = go.transform;
}
}
return trans;
}
I tried sorting the array by adding
var targetlist = enemies.OrderByDescending(item => item.GetComponent<sc_setpriorityclass>().setClass).ToArray();
and changing the foreach() loop to use this target list array instead. But it doesn't seem to have any effect, and the turrets still simply target the closest enemies.
Any help would be much appreciated thanks!
Are you replacing the distance check or want to check priority as well as distance?
try sorting it by distance and then by priority, then get the first or last element in list.