Help with adding collider to an array.

This is giving me a headache. I’ve been dealing with arrays for 2 days now without any effects. Basically im making a tower defense game and im trying to create a tower target acquisition system. My tower has a sphere trigger that collides with surrounding enemies. I need to add the colliding enemies to an array of “enemiesinrange”.

This is the current code:

I need to add colliders of the function OnTriggerEnter to the enemiesinrange array, this is my current code:

var enemiesinrange = new Array();
var objects : int = 0; //used to count the enemies in range, not really related.

function OnTriggerEnter (other : Collider) {
 
objects++;
enemiesinrange.Add(Collider);
print(other.BasicEnemy.age);
print(enemiesinrange[0].BasicEnemy.age);
}
Its supposed to add the "other" collider to my enemiesinrange array. It returns an error "Object reference not set to an instance of an object" on the following line:

**enemiesinrange.Add(Collider);**

Can anyone explain what im doing wrong / how to accomplish this?

I think you should do:

enemiesinrange.Add(other);

Cause other is the actual Collider :wink:

Tried that, it gives the same error.

First check if the collider is not null

if(other != null) {
   enemiesinrange.Add(other);
   ...

And I don’t know java but I think you’d be better of using a List rather than an Array.

It still doesnt work :confused:

Also whats the exact difference between List and Array? Is this sort of thing easier to do when youre using a list? Everyone says that arrays are way faster and ill be using a lot of turrets so i care about performance.

Edit: holy shit, the list actually works. thanks.

System.Array is faster than System.Collections.Generic.List however you’re using UnityEngine.Array which is basically crap and should never be used. If you need dynamic sizing and easy add/remove then use a List.

Null check before adding is unnecessary because the collider will never be null in OnTriggerEnter and adding null values to a collection is a legal operation.

Also - lines 8 and 9 in your code won’t work because BasicEnemy isn’t a member of Collider.

Oh, any idea how can i make that work? That would be really useful.

Make what work?

print(other.BasicEnemy.age);
print(enemiesinrange[0].BasicEnemy.age);

well, this, im trying to sort the objects by their age (int) and im not sure how to acces their “age” variable thats in their “BasicEnemy” script.

Use GetComponent to get the BasicEnemy script attached to the collider that triggered the…trigger.