How to execute a melee attack in Unity 3D

How to execute a melee attack in Unity 3D

Unity Editor, go to Window > Animation and select Create Animator Controller. Name your controller something like “Melee Attack” and click “Create”. Once you have your controller created, we’ll need to add some animations to it. In this example, we’re going to create an animation for swinging a sword.

  1. Create a new Sprite Renderer layer for the sword. Make sure the sword is positioned in front of the character and that it has a transparent background so you can see through it.

  2. Import an animation clip for swinging a sword. You can find these clips on the Unity Asset Store or create your own using software like Blender.

  3. Drag the sword sprite renderer into the Melee Attack controller in the Hierarchy view. This will allow us to control the sword’s animation from the script.

  4. In the Animator Controller, drag the sword sprite renderer onto the Sprite Renderer layer and select the Sword Swing animation clip.

Step 2: Scripting

With our animations created, we can now play them in our script. Here’s some sample code for this step:

csharp
// Play the melee attack animation
animator.SetInteger("Attack", 1);
// Wait for the animation to finish

IEnumerator PlayMeleeAttackAnimation(int attackHash)

{
animator.SetInteger("Attack", attackHash);

yield return new WaitForSeconds(0.5f); // Adjust the duration as desired

}

In this example, we’re using the animator.SetInteger() method to play an animation called “Attack”. We’ve also defined a function called PlayMeleeAttackAnimation() that takes in the hash of the attack animation and plays it for 0.5 seconds (you can adjust this as desired).

Step 3: Damage

The final step is to deal damage to the target of the attack. In this example, we’ll use a simple script that calculates damage based on the strength of the attack and the health of the target. Here’s some sample code for this step:

csharp
// Calculate the amount of damage to deal

float damage = attackStrength * Time.deltaTime; // Adjust the attackStrength variable as desired

// Check if the target is within range and has health left

if (target.transform.position.Distance(transform.position) < attackRange && target.health > 0)

{
// Take some health from the target

target.health -= damage;

// Play a particle effect to indicate damage was dealt

ParticleSystem ps = Instantiate(damageEffect, transform.position, Quaternion.identity);

ps.duration = damage / damageEffect.speed;

}

In this example, we’re using the attackStrength variable to determine how much damage to deal. We’re also checking if the target is within range and has health left before dealing damage. If both conditions are met, we’re taking some health from the target and playing a particle effect to indicate damage was dealt.

Putting it All Together

Now that we have all of the components in place, let’s put them all together! Here’s the complete code for our melee attack system:

csharp
using UnityEngine;
public class MeleeAttack : MonoBehaviour
{

    ps.duration = damage / damageEffect.speed;
public Transform attackRayOrigin; // The origin of the raycast
public LayerMask attackLayer; // The layer mask to check for hits
public float attackRange = 1f; // The range for the melee attack
public int attackStrength = 10; // The strength of the melee attack
public AnimatorController animatorController; // The animator controller for the melee attack
public GameObject damageEffect; // The particle effect for indicating damage was dealt
private RaycastHit hit; // A variable to hold the raycast hit information
private GameObject target; // A variable to hold the target of the melee attack
private float damage; // A variable to hold the calculated amount of damage to deal
void Update()
{
if (Input.GetButtonDown("Attack") && Physics.Raycast(attackRayOrigin.position, attackRayOrigin.forward, out hit, 1f, attackLayer))
{
target = hit.collider.gameObject;
damage = attackStrength * Time.deltaTime;
if (target.transform.position.Distance(transform.position) < attackRange && target.health > 0)
{
// Take some health from the target

target.health -= damage;

            // Play a particle effect to indicate damage was dealt

ParticleSystem ps = Instantiate(damageEffect, transform.position, Quaternion.identity);

ps.duration = damage / damageEffect.speed;

        }
    }
}
<h2>IEnumerator PlayMeleeAttackAnimation(int attackHash)</h2>
{
    animatorController.SetInteger("Attack", attackHash);

yield return new WaitForSeconds(0.5f); // Adjust the duration as desired

}

}

In this example, we’re using a public variable called attackStrength to determine how much damage to deal. We’re also using a public variable called damageEffect to specify the particle effect to use for indicating damage was dealt. Finally, we’re using the animatorController variable to play the melee attack animation from the script.

Summary

With our melee attack system in place, we can now create a character that can swing a sword and deal damage to enemies! With some tweaking, this system can be extended to include additional animations, more advanced damage calculation, and even AI-controlled enemies that can dodge and block attacks.