- Home /
How to do a check if an Array is empty?
I have a basic melee system implemented with a large cube trigger collider attached to the front of my player that gets enabled briefly on Input Fire1. My problem was, I only wanted it to be able to hit one person (it was calling the ApplyDamage function on all enemies in the cube in front of the player, even though I set it to deactivate itself after sending the ApplyDamage message in OnTriggerEnter).
So I came up with a simple solution I was rather proud of :) I created an Array called enemies, and add the enemy GameObject to the Array OnTriggerEnter. The in LateUpdate, I check if enemies[0] is null, and if not, call the ApplyDamage function on enemies[0] and clear the Array.
However, it throws an error when I check if enemies[0] == null, saying that "ArgumentOutOfRangeException: Index is less than 0 or more than or equal to the list count." Is there another way I can check if the enemies Array is empty?
Here's my code:
private var enemies = new Array();
function LateUpdate(){
if(enemies[0] != null){
enemies[0].GetComponent(EnemyStatus).ApplyDamage();
enemies.Clear();
}
}
function OnTriggerEnter (other : Collider) {
if(other.gameObject.tag == "Enemy"){
enemies.Add(other.gameObject);
gameObject.active = false;
}
}
Answer by Anton S. · Dec 02, 2010 at 03:22 PM
Try this:
if(enemies.length > 0){
enemies[0].GetComponent(EnemyStatus).ApplyDamage();
enemies.Clear();
}
Answer by Mince_AT_FC · Dec 08, 2015 at 11:59 AM
Nope.
enemies.length
<-- this value is not the index, it's what can be expected : amount of items in the array. If it's 0 it's an empty array.
Your answer

Follow this Question
Related Questions
Removing null object from array in unity 0 Answers
Populate an array of GameObjects with collision? 1 Answer
String in array is null when checking length, help bug?! 2 Answers
Avoiding adding duplicate objects to ArrayList 2 Answers
Why is my C# array of objects fully populated when some of them should be null? 3 Answers