- Home /
How to add colliders to an array, and pick the oldest one?
Im trying to make a tower defense game and i need a tower targetting system that picks the oldest object (the enemy closest to the end) in its range and shoots at it until the object dies, then picks a new target. Each enemy object has a "age" variable that's its age in seconds.
How do i add the enemies in range to my enemiesinrange array? I need it to return the oldest object so that the turret can target it.
The following part doesn't compile:
if(enemiesinrange.length > 0) {
var oldestEnemy = enemiesinrange[0];
var age = Collider.age;
for (var i = 0; i < array.Count() - 1; i++) {
if (array[i].age > array[oldestIndex].age) {
oldestIndex = i;
}
}
print(oldestEnemy);
}
Here's the code of the entire function:
function OnTriggerStay (other : Collider) {
if(other.gameObject.CompareTag("Enemy")){
selectedTarget = other;
isidle=0;
if(enemiesinrange.length > 0) {
var oldestEnemy = enemiesinrange[0];
var age = Collider.age;
for (var i = 0; i < array.Count() - 1; i++) {
if (array[i].age > array[oldestIndex].age) {
oldestIndex = i;
}
}
print(oldestEnemy);
}
}
Answer by MakeCodeNow · May 19, 2014 at 11:20 PM
It's maybe easiest to just sort the list. Something like this:
Array.Sort(enemiesinrange, delegate(MyEnemyType a, MyEnemyType b)
{
if(a.age > b.age)
return 1;
else if(a.age < b.age)
return -1;
else
return 0;
});
var oldestEnemy = enemiesinrange[0];
I need to add the colliders to the enemiesinrange array, ill make use of your sorting code after I do that.
var enemiesinrange = new Array();
var objects : int = 0;
function OnTriggerEnter (other : Collider) {
objects++;
enemiesinrange.Add(Collider);
print(other.BasicEnemy.age);
print(enemiesinrange[0].BasicEnemy.age);
}
This is my current code, its supposed to add the collider to my enemiesinrange. It returns an error "Object reference not set to an instance of an object" on the following line:
enemiesinrange.Add(Collider);
That means that enemiesinrange is null. You probably are not assigning it to anything when you declare it. It probably needs an = new List() or new SomeType[] or something like that. I'm not sure because you don't show the declaration here, but that's likely the problem.
Your answer
Follow this Question
Related Questions
Adding a collider to array 1 Answer
Can't click gameobject when over another trigger? 1 Answer
Script error: OnTriggerEnter 1 Answer
Check for rigidbody presence when in collision with a trigger 2 Answers
Collision returning an error 0 Answers