Implementing Melee Attacks in Unity
Melee attacks are a fundamental part of many action and RPG games. In this tutorial, we'll create a simple melee attack system in Unity using C#.
Setting Up the Character
To begin, ensure you have a character with an Animator and a Collider (e.g., a BoxCollider or SphereCollider) attached.
Creating the Melee Attack Script
Create a new C# script and name it MeleeAttack. Attach this script to your player or character GameObject.
using UnityEngine;
public class MeleeAttack : MonoBehaviour
{
public float attackRange = 1.5f;
public int attackDamage = 20;
public Transform attackPoint;
public LayerMask enemyLayers;
public Animator animator;
void Update()
{
if (Input.GetMouseButtonDown(0)) // Left mouse click for attack
{
Attack();
}
}
void Attack()
{
// Play attack animation
animator.SetTrigger("Attack");
// Detect enemies in attack range
Collider[] hitEnemies = Physics.OverlapSphere(attackPoint.position, attackRange, enemyLayers);
// Damage enemies
foreach (Collider enemy in hitEnemies)
{
enemy.GetComponent<EnemyHealth>()?.TakeDamage(attackDamage);
}
}
}
Adding Enemy Health Script
To make sure enemies take damage, create an EnemyHealth script:
using UnityEngine;
public class EnemyHealth : MonoBehaviour
{
public int health = 100;
public void TakeDamage(int damage)
{
health -= damage;
Debug.Log(gameObject.name + " took " + damage + " damage.");
if (health <= 0)
{
Die();
}
}
void Die()
{
Destroy(gameObject);
}
}
Setting Up Attack Point
- Create an empty GameObject as a child of your character.
- Position it in front of the character (where the attack should hit).
- Assign it to the
attackPointvariable in theMeleeAttackscript.
Configuring the Animator
Ensure your Animator has an "Attack" trigger parameter. Assign a melee attack animation to it in the Animator Controller.
Final Thoughts
Now, pressing the left mouse button will trigger an attack, playing an animation and damaging nearby enemies. You can expand this system with combo attacks, different weapon types, or even adding force to enemies when hit.
Happy coding! 🚀