Attack/Targeting Script Issue

Hello! I have those two scripts below. What they basically allow me to do is to kind of attack an enemy if the mouse cursor is on the object. The issue here is when i have multiple enemies. For some reason i cannot attack whichever enemy i want and i have to start by killing the last one i placed in the scene :S Is there a way to fix this? Thanks!

MeleeDamage.js

var mDPS : int;
var oDPS : int;

function mainhand(){
	mDPS = 8;
}

function offhand(){
	oDPS = 4;
}

function Update(){
	if(Input.GetKeyDown(KeyCode.R)){
		mainhand();
		Debug.Log("MainHand Equipped!");
	}
	if(Input.GetKeyDown(KeyCode.T)){
		offhand();
		Debug.Log("OffHand Equipped!");
	}
	enemy = GameObject.FindWithTag("enemy");
	var enScript = enemy.GetComponent(Enemy);
	if(enScript.readyforattack){
		if(Input.GetMouseButtonDown(0)){
			damage();
		}	
	}
}	
	

function damage(){
	enemy = GameObject.FindWithTag("enemy");
	var enScript = enemy.GetComponent(Enemy);
	var statScript = transform.GetComponent(Attributes);
	dmg = mDPS + oDPS + (statScript.STRENGTH/2);
	enScript.health -= dmg;
	statScript.recalculateStats();
	Debug.Log(dmg);
}

Enemy.js

var health : int = 20;
var readyforattack : boolean = false;

function Update(){
	if(health <= 0){
		Destroy(gameObject);
	}
}

function OnMouseOver(){
	readyforattack = true;
}

function OnMouseExit(){
	readyforattack = false;
}

Hello. The Problem is this line:

enemy = GameObject.FindWithTag("enemy");

If you got more than one enemy, it will only return one.

You can do the following to fix that: Add a Collider marked as Trigger to the Player. If you already have a collider, use a child gameobject, if you need help with that, just ask.

Add the following to a script on the player:

    // sorry for csharp i dont use unityscript :)
    // put this on player
    
    // on top
    
    // in start or awake 

    List<Enemy> InRange = new List<Enemy>();
    
    // function for the trigger you put on the player object
    
    void OnTriggerEnter(Collider collider)
    {
        if (collider.tag == "Enemy")
        {
            InRange.Add(collider.gameObject.GetComponent<Enemy>());
        }
    }


    void OnTriggerExit(Collider collider)
    {
        if (collider.tag == "Enemy")
        { 
        InRange.Remove(collider.transform.GetComponent<Enemy>())
        }   
    }

    // Now in your attack function you can do the damage loop:

    void YourAttackFunction()
    {
        for (int x = 0; x < InRange.Count; x++)
        {
            InRange[x].ApplyDamage();
        }
    
    }
    
}

Note 1: There are many more possible way to do this, using raycasting to the middle of the screen for instance. If you want to know moreā€¦ :slight_smile:

Note 2: Sorry I will need to find out how to format things properly here, tab is not working for me