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?
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.
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.