I have recently been trying to implement a combat system to my game. When I finished making the scripts, I tried to test it out. I set the attack damage to 20 and the enemy’s max health to 100. When i attacked the enemy, the health went to -20. I tried changing the damage to -20 but now it goes to 20. I also cannot attack the enemy twice.
edit: the version of unity i am using is 2020.3.0f1
Here are the scripts I used:
Script 1
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ENEMY : MonoBehaviour
{
public int maxHealth = 100;
int currenthealth;
// Start is called before the first frame update
void Start()
{
currenthealth = maxHealth;
}
public void TakeDamage(int damage)
{
currenthealth -= damage;
//Play a hurt animation
if(currenthealth <= 0)
{
Die();
}
void Die()
{
Debug.Log("enemy died");
// play die animation
// disable the enemy
}
}
}
Script 2
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PLAYER_COMBAT : MonoBehaviour
{
public Animator animator;
public Transform attackPoint;
public LayerMask enemyLayers;
public float attackRange = 0.5f;
public int attackDamage = 20;
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Mouse0))
{
Attack();
}
}
void Attack()
{
// play attack animation
animator.SetTrigger("Attack");
// detect enemies in range of the attack
Collider[] hitEnemies = Physics.OverlapSphere(attackPoint.position, attackRange, enemyLayers);
// damage the enemy
foreach (Collider enemy in hitEnemies)
{
enemy.GetComponent<Enemy>().TakeDamage(attackDamage);
}
}
void OnDrawGizmosSelected()
{
if (attackPoint == null)
return;
{
Gizmos.DrawWireSphere(attackPoint.position, attackRange);
}
}
}
As you may be able to tell, I haven’t set up a dying animation or disabled the enemy after it died yet