- Home /
Combat Script
The foundation for this code is not mine however I have added some elements. I want to be able to target all enemies in the array and then be able to attack them. What do I need to modify or add to this code to do so? Thanks in advance.
var enemyTarget : GameObject[];
var range : int = 2;
var countDown : int = 0;
var coolDown : int = 2;
var swordOut : boolean = false;
function Update ()
{
Targets();
if(swordOut)
{
if(countDown > 0)
{
countDown -= 1 * Time.deltaTime;
}
if(countDown < 0)
{
countDown = 0;
}
if(Input.GetKeyUp(KeyCode.E))
{
Swing();
}
}
}
function Targets ()
{
enemyTarget[0] = GameObject.FindWithTag("enemy");
enemyTarget[1] = GameObject.FindWithTag("enemy");
}
function Swing()
{
var distance : int = Vector3.Distance(enemyTarget.transform.position, transform.position);
var dir = (enemyTarget.transform.position - transform.position).normalized;
var direction = Vector3.Dot(dir, transform.forward);
if(distance <= 3)
{
if(direction > 0)
{
enemyTarget.GetComponent(enemyHealth).currentEnemyHealth -= 35;
}
}
}
Answer by Esa · Feb 09, 2012 at 07:05 AM
Presumably all enemies have some sort of identification variable in them. So you could for/foreach-loop through all of them to find the right one or if you want to attack all of them at once just loop through all the enemies with either of the forementioned loops.
Answer by Berenger · Feb 09, 2012 at 06:51 AM
If your enemies have a collider, you should use Physic.OverlapSphere, which returns the an array of colliders at a given radius, so you don't need to look for them with Find anymore.
Then, use a loop on that array and decrease the health of each elements.
PS : It's not a big deal, but the way you handle countdown in Update is bugging me, take a look at Mathf.Clamp.
Your answer
![](https://koobas.hobune.stream/wayback/20220613063912im_/https://answers.unity.com/themes/thub/images/avi.jpg)