- Home /
how to sort a list of gameobjects?
I am making a tower defense game and i need to find the object that is the one closest to the target (the one that has traveled the farthest) and shoot it. i have most of the code set up but i need to sort it by the "distanceTraveled variable". thanks in advance!
using UnityEngine; using System.Collections; using System.Collections.Generic;
public class Tower : MonoBehaviour {
public bool firing;
public Transform mon;
public GameObject bulletPrefab;
public bool running = true;
public List<GameObject> enemyList;
private Transform toShoot;
// Use this for initialization
void Start () {
ScoreManager.score = ScoreManager.score - 100;
StartCoroutine (shoot ());
}
// Update is called once per frame
void Update () {
transform.Rotate (Vector3.up * Time.deltaTime * 35, Space.World);
if (enemyList.Count > 0) {
if (enemyList[0] == null) {
enemyList.RemoveAt(0);
}
}
}
void OnTriggerEnter(Collider co){
if (co.GetComponent<Monster> ())
{
enemyList.Add(co.gameObject);
}
}
void OnTriggerExit(Collider co){
if (co.GetComponent<Monster> () && co.transform == enemyList[0].transform)
{
enemyList.RemoveAt(0);
}
}
IEnumerator shoot(){
while (running) {
if (enemyList.Count > 0){
GameObject b = (GameObject)Instantiate (bulletPrefab, transform.position, Quaternion.identity);
b.GetComponent<Bullet> ().target = enemyList[0].transform;
yield return new WaitForSeconds (1.0f);
}
else
{
yield return new WaitForSeconds(0.1f);
}
}
}
}
using UnityEngine; using System.Collections;
public class Monster : MonoBehaviour {
private float distanceTraveled;
private NavMeshAgent NMA;
// Use this for initialization
void Start () {
NMA = GetComponent<NavMeshAgent> ();
GameObject castle = GameObject.Find("Castle");
if (castle)
NMA.destination = castle.transform.position;
}
void Update(){
distanceTraveled = NMA.remainingDistance;
}
void OnTriggerEnter(Collider co) {
if (co.name == "Castle") {
co.GetComponentInChildren<Health>().decrease();
Destroy(gameObject);
}
}
}
Answer by Cherno · Sep 20, 2015 at 08:46 PM
Write a simple compare function:
private int CompareDistanceTravelled(GameObject a, GameObject b) {
float distance_a = a.GetComponent<Monster>().distanceTraveled;
float distance_b = b.GetComponent<Monster>().distanceTraveled;
if(a >= b) {
return 1;
}
else {
return -1;
}
}
Sort the list with the Sort() function and pass it your sorting function.
enemyList.Sort(CompareDistanceTravelled);
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
A node in a childnode? 1 Answer
Check if all values in a list are equal 1 Answer
Make Lists within a List 0 Answers