melee combat

when the enemy or multiple enemys gets in range of the melee swing then send them a adjust health command to remove some hitpoints…

i really cant get the hang of unitys way of doing things / syntax . can someone help me out

thanks

The easiest way is like you said: remove health from the enemy when the player attacks AND the enemy is in the attack range. You can find all enemies in the range using Physics.OverlapSphere: it returns an array with all colliders whose bounds touch an imaginary sphere of given radius. This must be used just as an approximation: bounds are boxes aligned to the world axes, thus the attack range may be up to 70% larger depending on the enemy position. To avoid this, you must verify if the objects hit by the sphere are inside the attack range; if yes, use SendMessage (see below) to apply the damage.

Child an empty object to the player, and adjust its position to be the center of the melee attack, then attach to it the script below:

var range: float = 1.8;
var attackInterval: float = 0.7;
var meleeDamage: float = 30;
private var nextAttack: float = 0;

function MeleeAttack(){
  if (Time.time > nextAttack){ // only repeat attack after attackInterval
    nextAttack = Time.time + attackInterval;
    // get all colliders whose bounds touch the sphere
    var colls: Collider[] = Physics.OverlapSphere(transform.position, range);
    for (var hit : Collider in colls) {
      if (hit && hit.tag == "Enemy"){ // if the object is an enemy...
        // check the actual distance to the melee center
        var dist = Vector3.Distance(hit.transform.position - transform.position);
        if (dist <= range){ // if inside the range...
          // apply damage to the hit object
          hit.SendMessage("ApplyDamage", meleeDamage);
        }
      }
    }
  }
}

function Update(){
  if (Input.GetButtonDown("Fire1")){
    MeleeAttack();
  }
}

The instruction component.SendMessage(“function”, value) actually calls the “function(value)” in the component object, thus you must add the damage function to the enemy script:

var health: float = 100;

function ApplyDamage(damage: float){
  if (health > 0){ // if enemy still alive (don't kick a dead dog!)
    health -= damage; // apply the damage...
    // <- enemy can emit some sound here with audio.Play();
    if (health <= 0){ // if health has gone...
      // enemy dead: destroy it, explode it etc.
    }
  }
}

NOTE: This is the simplest melee attack - you can hurt even enemies behind you, if the range and/or the “melee position” are badly chosen. A more sophisticated approach would require to have a trigger attached to the melee, which would apply damage only to the enemies actually hit, but this one works well enough in many cases.