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.