- Home /
Resize Array Based on Value
Hello, i am making a 3D Tower Defense Game and I'm currently stuck on the targeting system, Specifically First and Last Targeting. Closest, strongest and weakest works fine. I belive i am on the good track when it comes to its logic but i dont know how to resize array based on value. Let me explain the system first. Every enemy has crossed times (ammount of times it has turned a corner) and distance to that corner it has to turn which is defined as a point. First targeting works by checking which enemy has the largest ammount of crossed times and lowest ammount of distance to the point its heading towards. Now i dont know how to make the array only count enemies with the largest ammount of crosses and not all of them. Any help is appreciated and here is my code for First targeting
List targets2 = new List(); Collider[] colliders2 = Physics.OverlapSphere(transform.position, Range, layers); collidersCheck = colliders2;
for (int i = 0; i < colliders2.Length; i++)
{
valuesINT = new int[colliders2.Length];
for (int i2 = 0; i2 < colliders2.Length; i2++)
{
valuesINT[i2] = colliders2[i2].GetComponent<Enemy>().CrossedTimes;
}
SingleValueINT = Mathf.Max(valuesINT);
if (colliders2[i].GetComponent<Enemy>().CrossedTimes == SingleValueINT)
{
valuesFLOAT = new float[colliders2.Length];
for (int i2 = 0; i2 < colliders2.Length; i2++)
{
valuesFLOAT[i2] = colliders2[i2].GetComponent<Enemy>().DistanceToExit;
}
SingleValueFLOAT = Mathf.Min(valuesFLOAT);
if (colliders2[i].GetComponent<Enemy>().DistanceToExit == SingleValueFLOAT)
{
FirstEnemy = colliders2[i].GetComponent<Enemy>();
tower.Target = FirstEnemy;
}
}
}
if(colliders2.Length == 0)
{
tower.Target = null;
}
Answer by Developers_Hub · Jan 16 at 06:23 PM
You can use Linq to sort lists based on multiple values. Take a look at this and see if it can help you.
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class Tower : MonoBehaviour
{
public float range = 5;
public LayerMask layers;
private void Update()
{
Enemy target = GetClosestEnemyToFinishLine();
if(target != null)
{
// Shoot the target
}
}
private Enemy GetClosestEnemyToFinishLine()
{
Collider[] colliders = Physics.OverlapSphere(transform.position, range, layers);
List<Enemy> enemies = new List<Enemy>();
if(colliders != null && colliders.Length > 0)
{
for (int i = 0; i < colliders.Length; i++)
{
Enemy enemy = colliders[i].GetComponent<Enemy>();
if (enemy != null)
{
enemies.Add(enemy);
}
}
}
if(enemies.Count > 0)
{
enemies = enemies.OrderByDescending(c => c.CrossedTimes).ThenBy(n => n.DistanceToExit).ToList<Enemy>();
return enemies[0];
}
return null;
}
}
Answer by GhostSlayer44 · Jan 16 at 07:48 PM
Can't thank you enough man. Works like a charm, thanks for the help!