Script only works in the order of the hierarchy

Hi everyone

I’ve written a script which I use to attack enemies (tagged Enemy). It’s attached to a collider with IsTrigger active. It works, but only if you attack the enemies in the exact order in which they’re placed in the Hierarchy panel.

var otherobject : GameObject;
var cooldown : boolean = false;
var activetexture : GUIStyle;
var inactivetexture : GUIStyle;
var usedtexture : GUIStyle;
var enemyhealth : EnemyHealth;
static var interval : float;


function Start (){

usedtexture = activetexture; 
interval = 10;

}


function OnTriggerStay(Trigger : Collider){
if (Trigger.tag == "Enemy" && otherobject == null){
otherobject = Trigger.gameObject;
enemyhealth = otherobject.GetComponent(EnemyHealth);
}
else {
otherobject = null;
enemyhealth = null;
}
}

function OnGUI (){
if (GUI.Button (Rect(0,500,100,100),GUIContent("Attack"),usedtexture) && otherobject != null && cooldown == false){
enemyhealth.enemyhealth -= 50;
cooldown = true;
Timer();
}
}



function Timer (){

if(cooldown == true){
usedtexture = inactivetexture;
yield WaitForSeconds(interval);
cooldown = false;
usedtexture = activetexture;
}
}

How can I make Unity accept all the GameObject which have the tag Enemy?

Well, if you are going to be attacking more than one enemy at a time then you will need a reference to more than 1 so use an array to store the enemies that are within range in.

http://unity3d.com/support/documentation/ScriptReference/Array.html

e.g.

var enemies : GameObject;

function OnTriggerStay(Trigger : Collider)
{

if(trigger.CompareTag("Enemy"))
{
    add me to array, enemies[];
}

}

It still doesn’t work. I rewrote my script like this, using arrays like you said:

var enemies : GameObject[];
var cooldown : boolean = false;
var activetexture : GUIStyle;
var inactivetexture : GUIStyle;
var usedtexture : GUIStyle;
var enemyhealth : EnemyHealth;
static var interval : float;


function Start (){

usedtexture = activetexture; 
interval = 10;

}


function OnTriggerStay(trigger : Collider){
if (trigger.CompareTag("Enemy")){
enemies.Push(trigger);
}
}

function OnGUI (){
if (GUI.Button (Rect(0,500,100,100),GUIContent("Attack"),usedtexture) && enemies!=null && cooldown == false){
enemies.enemyhealth -= 50;
cooldown = true;
Timer();
}
}



function Timer (){

if(cooldown == true){
usedtexture = inactivetexture;
yield WaitForSeconds(interval);
cooldown = false;
usedtexture = activetexture;
}
}

But it still just accepts the enemies in a specific order.
I think that Unity thinks that there’s can only be 1 object with the tag Enemy.