Instead of using range i was thinking about giving damage when weapon hits enemies collider. I have put a box collider around players weapon and set it to is trigger. Then in fighter script i have added this code in the hit event. Here I pass inn the target, damage and gameobject to a function i have added in the weapon script.
if(target.gameObject.name == "Player")
{
currentWeapon.value.GiveMeeleDamage(target, damage, gameObject);
}
else if (target.gameObject.name != "Player" && Input.GetKeyDown(0))
{
currentWeapon.value.GiveMeeleDamage(target, damage, gameObject);
}
Then in the weapon script i set the target, damage, instigator and a boolean that we are hitting the enemy to true. I set this to true when we swing the sword and false after we have given damage so we cant give damage to enemy just by touching him with the sword. But the problem is that if I swing the sword without being close enough to the enemy the boolean is set to true and if i then run up to the enemy i give damage if the box collider around the sword touches the enemy without swinging. Any ideas how i can work around this?
public void GiveMeeleDamage(Health target, float damage, GameObject instigator)
{
this.target = target;
this.damage = damage;
this.instigator = instigator;
hasHit = true;
}
// gives damage when weapon hits target.
private void OnTriggerEnter(Collider other)
{
// since target is of type health can check if its targets health we are hitting.
if (other.GetComponent<Health>() != target) return;
// if we dont have a target just stop, dont get null reference error.
if (target == null) return;
if (target.IsDead()) return;
// has hit is only true if hit weapon animation reaches hit in fighter script, only then give dmg.
// so we dont give damage when player or enemy only touches the other weapon.
if (hasHit)
{
target.TakeDamage(instigator, damage);
hasHit = false;
}
}