0% found this document useful (0 votes)
23 views24 pages

Hit System With Interfaces in Unity - by Jared Amlin - Nerd For Tech - Medium

Uploaded by

AlexandreJunior
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views24 pages

Hit System With Interfaces in Unity - by Jared Amlin - Nerd For Tech - Medium

Uploaded by

AlexandreJunior
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

07/06/24, 17:42 Hit System with Interfaces in Unity | by Jared Amlin | Nerd For Tech | Medium

This member-only story is on us. Upgrade to access all of Medium.

Member-only story

Hit System with Interfaces in Unity


Jared Amlin · Follow
Published in Nerd For Tech
7 min read · Mar 22, 2024

Listen Share More

Have you ever wondered how first and third person shooter games handle their hit
system? You know the kind I am talking about, where headshots will kill an
opponent while a body or limb shot will take more than one hit. Then you get
various animations that play depending on where the enemy was hit when they took
damage or died.

https://medium.com/nerd-for-tech/hit-system-with-interfaces-in-unity-dfb93b3537a5 1/24
07/06/24, 17:42 Hit System with Interfaces in Unity | by Jared Amlin | Nerd For Tech | Medium

Most of the damage implementation I have done in the past involved a single object
with a collider on it. I have to admit, I still have no idea how AAA gaming studios
construct their hit systems, but this is the solution I came up with, using the Unity
Documentation as my only resource.

Scripting

I wanted to make this system scalable, reusable, and designer friendly, so I got
started with an Interface! This IHittable interface is the base class for all objects that
need to be hit. This is what a Raycast from a gun object or camera will use to pass in
a damage amount to the inheriting class, which leaves flexibility for more weapons
to pass in their own various amount of base damage.

public interface IHittable


{
void HitDamage(int damageAmount);
}

The Hit class, inherits from both MonoBehavior and IHittable. Multiple inheritance is
of course, one of the many benefits of using interfaces. This script can be attached
to any object with a collider that you want to be hit.
All Serialized Fields are assigned per script instance in the inspector.

The inherited Hit Damage method takes the incoming damage amount and
multiplies it by it’s hit multiplier value, then passes the new multiplied damage
amount to the IDamageable interface on the main parent object. The hitTrigger string
names assigned in the inspector need to perfectly match the name of the Trigger
parameter in the animator that you want to use, when this object is hit. Here I
reference two triggers, one for a hit reaction animation, and another for a death
animation. The Animation Clip variable is the animation you want to be triggered.

https://medium.com/nerd-for-tech/hit-system-with-interfaces-in-unity-dfb93b3537a5 2/24
07/06/24, 17:42 Hit System with Interfaces in Unity | by Jared Amlin | Nerd For Tech | Medium

This will get the length of the animation to pass in as a time value to stop the enemy
agent from moving, until the hit animation completes.

public class Hit : MonoBehaviour, IHittable


{
[SerializeField] private int _hitMultiplier;

[SerializeField] private string _hitTrigger;

[SerializeField] private string _deathTrigger;

[SerializeField] private AnimationClip _animationClip;

private float _clipLength;

private IDamageable enemyDamageable;

private void Start()


{
enemyDamageable = GetComponentInParent<IDamageable>();

_clipLength = _animationClip.length;
}

public void HitDamage(int damageAmount)


{
int damage = damageAmount * _hitMultiplier;

enemyDamageable.Damage(damage, _hitTrigger, _deathTrigger, _clipLength)


}
}

The IDamageable interface uses a health property with a getter. The damage method
takes parameters for the damage amount, string trigger names, and clip length
coming in from the Hit class.

public interface IDamageable


{
int Health { get; }

https://medium.com/nerd-for-tech/hit-system-with-interfaces-in-unity-dfb93b3537a5 3/24
07/06/24, 17:42 Hit System with Interfaces in Unity | by Jared Amlin | Nerd For Tech | Medium

void Damage(int damageAmount, string triggerName, string deathTriggerName,


}

The enemy class inherits from MonoBehavior and the IDamageable interface. The
important variables for this article are the Animator, and the inherited health
property and health variables.

The damage method takes in the parameter of the damage amount, and subtracts it
from the current health value. The health is checked to see if the enemy is dead, and
if death has run it’s course, the animator is triggered and passes in the string value
being passed in from the hit class. If there is life yet to be lived, the hit reaction
string value is triggered instead.
A coroutine is used to wait for the animation clip length to finish playing, before
moving the enemy agent again.

public class Enemy : MonoBehaviour, IDamageable


{
[SerializeField] private Transform _playerTransform;

[SerializeField] private NavMeshAgent _agent;

[SerializeField] private Animator _animator;


private float _clipLength;

[SerializeField] private int _startingHealth;


[SerializeField] private int _currentHealth;

private const string _waitRoutine = "WaitForAnimation";

private bool _isDead = false;

public int Health


{
get
{
return _currentHealth;
}
}

https://medium.com/nerd-for-tech/hit-system-with-interfaces-in-unity-dfb93b3537a5 4/24
07/06/24, 17:42 Hit System with Interfaces in Unity | by Jared Amlin | Nerd For Tech | Medium

private void Start() Open in app


{
_animator = GetComponent<Animator>();
Search

_currentHealth = _startingHealth;
}

// Update is called once per frame


void Update()
{
_agent.destination = _playerTransform.position;
}

private void Die()


{
Debug.Log("Enemy is DEAD");
}

public void Damage(int damageAmount, string triggerName, string deathTrigge


{
StopCoroutine(_waitRoutine);

_agent.isStopped = true;

_currentHealth -= damageAmount;

Debug.Log("Animation clip length " + clipLength);

if (_currentHealth > 0)
{
_animator.SetTrigger(triggerName);

SetClip(clipLength);

StartCoroutine(_waitRoutine);
}
else
{
if (!_isDead)
{
_isDead = true;

_animator.SetTrigger(deathTriggerName);

Die();
}
}
}

private IEnumerator WaitForAnimation()


{
float waitTime = GetClip();

https://medium.com/nerd-for-tech/hit-system-with-interfaces-in-unity-dfb93b3537a5 5/24
07/06/24, 17:42 Hit System with Interfaces in Unity | by Jared Amlin | Nerd For Tech | Medium

yield return new WaitForSeconds(waitTime);

_agent.isStopped = false;
}

private void SetClip(float clipLength)


{
_clipLength = clipLength;
}

private float GetClip()


{
return _clipLength;
}
}

Everything begins here where the player shoots a raycast forward from the center of
the screen. All it needs to do is check if the hit object has an IHittable interface, and
if it does, pass in a damage amount.

private void Shoot_performed(InputAction.CallbackContext context)


{
//shoot
print("Shooting!");

//raycast forward from screen center


Ray rayOrigin = Camera.main.ViewportPointToRay(_centerPoint);

//store hit info


RaycastHit hitInfo;

if (Physics.Raycast(rayOrigin, out hitInfo))


{
Debug.Log("Hit object " + hitInfo.collider.name);

IHittable hit = hitInfo.collider.GetComponent<IHittable>();

if (hit != null)
{
hit.HitDamage(10);
//Instantiate(_bloodVFX, hitInfo.point + hitInfo.normal, Quater

https://medium.com/nerd-for-tech/hit-system-with-interfaces-in-unity-dfb93b3537a5 6/24
07/06/24, 17:42 Hit System with Interfaces in Unity | by Jared Amlin | Nerd For Tech | Medium

Instantiate(_bloodVFX, hitInfo.collider.transform.position, Qua


}
}

_gunInterface.Play();

_muzzleFlash.SetActive(true);
}

Colliders and Inspector

Each object that needs to be hit has a capsule collider. I used 10 colliders in this
example (head, torso, left and right arms and legs with upper and lower colliders), but
feel free to use as many or as few as you need.

I used the corresponding rig objects as the parents for the respective colliders, so
that they move with the model. This is a Mixamo rig (thanks Adobe!), and here is the
head rig object with a collider and an instance of the Hit script.

https://medium.com/nerd-for-tech/hit-system-with-interfaces-in-unity-dfb93b3537a5 7/24
07/06/24, 17:42 Hit System with Interfaces in Unity | by Jared Amlin | Nerd For Tech | Medium

Another example showing the left arm colliders.

You can see the Hit script on the spine has a hit multiplier of 10, strings for the Body
Hit and Body Death animations, and the Hit to Body reaction animation being used.

https://medium.com/nerd-for-tech/hit-system-with-interfaces-in-unity-dfb93b3537a5 8/24
07/06/24, 17:42 Hit System with Interfaces in Unity | by Jared Amlin | Nerd For Tech | Medium

Animator

The first things first, let’s make Trigger parameters in the Animator for every
different animation you want to play.

https://medium.com/nerd-for-tech/hit-system-with-interfaces-in-unity-dfb93b3537a5 9/24
07/06/24, 17:42 Hit System with Interfaces in Unity | by Jared Amlin | Nerd For Tech | Medium

There is probably a more elegant way to handle the Animator than this default
window, so bear with me. Other than the Rifle Walk as the entry state, all other hit
and death clips are triggered from Any State.

https://medium.com/nerd-for-tech/hit-system-with-interfaces-in-unity-dfb93b3537a5 10/24
07/06/24, 17:42 Hit System with Interfaces in Unity | by Jared Amlin | Nerd For Tech | Medium

The transitions from Any State have no Exit Time, so it is very responsive when
jumping between hit animations before the previous one has finished playing. Each
transition has one Condition, that is the matching Trigger name.

Here is another example with the death from a body shot transition.

https://medium.com/nerd-for-tech/hit-system-with-interfaces-in-unity-dfb93b3537a5 11/24
07/06/24, 17:42 Hit System with Interfaces in Unity | by Jared Amlin | Nerd For Tech | Medium

The only transitions with exit times are the ones going from the hit reaction
animations back to the default Rifle Walk state.

https://medium.com/nerd-for-tech/hit-system-with-interfaces-in-unity-dfb93b3537a5 12/24
07/06/24, 17:42 Hit System with Interfaces in Unity | by Jared Amlin | Nerd For Tech | Medium

Results

Body and Leg hits.

Arm hits.

Head hits.

https://medium.com/nerd-for-tech/hit-system-with-interfaces-in-unity-dfb93b3537a5 13/24
07/06/24, 17:42 Hit System with Interfaces in Unity | by Jared Amlin | Nerd For Tech | Medium

Headshot.

Body Death

https://medium.com/nerd-for-tech/hit-system-with-interfaces-in-unity-dfb93b3537a5 14/24
07/06/24, 17:42 Hit System with Interfaces in Unity | by Jared Amlin | Nerd For Tech | Medium

Arm Death

Leg Death

https://medium.com/nerd-for-tech/hit-system-with-interfaces-in-unity-dfb93b3537a5 15/24
07/06/24, 17:42 Hit System with Interfaces in Unity | by Jared Amlin | Nerd For Tech | Medium

Compilation

Feel free to let me know in the comments how YOU would put together a hit system,
and thanks for reading!

Unity Game Development Unity3d Interfaces Fps Games

Game Development

https://medium.com/nerd-for-tech/hit-system-with-interfaces-in-unity-dfb93b3537a5 16/24
07/06/24, 17:42 Hit System with Interfaces in Unity | by Jared Amlin | Nerd For Tech | Medium

Follow

Written by Jared Amlin


435 Followers · Writer for Nerd For Tech

I am an artist and musician, that is currently diving headfirst into game development with C# and Unity3D.

More from Jared Amlin and Nerd For Tech

Jared Amlin

Understanding Frustum and Occlusion Culling in Unity3D


You may have heard of these terms before, but what do they really mean? Let’s break this down
piece by piece, and then get into using…

· 5 min read · Jan 5, 2022

https://medium.com/nerd-for-tech/hit-system-with-interfaces-in-unity-dfb93b3537a5 17/24
07/06/24, 17:42 Hit System with Interfaces in Unity | by Jared Amlin | Nerd For Tech | Medium

Ronak Patel in Nerd For Tech

Best 5 Micro Front-end Frameworks Every Developer Should Know


In today’s dynamic landscape of web development, the demand for scalable, agile and
maintainable solutions has never been more pressing. As…

7 min read · Apr 18, 2024

125

https://medium.com/nerd-for-tech/hit-system-with-interfaces-in-unity-dfb93b3537a5 18/24
07/06/24, 17:42 Hit System with Interfaces in Unity | by Jared Amlin | Nerd For Tech | Medium

Yashu Gupta in Nerd For Tech

Chat GPT and GPT 3 Detailed Architecture Study-Deep NLP Horse


A detailed intuition and methodology behind the GPT and Chat GPT Language Models.

9 min read · Mar 2, 2023

119 2

Jared Amlin

New Unity Input System: Player Rotation


Now that the player is moving with two different Action Maps and the WASD keys, let’s get the
player rotating with the arrow keys and mouse…

· 4 min read · Dec 11, 2022

See all from Jared Amlin

See all from Nerd For Tech

https://medium.com/nerd-for-tech/hit-system-with-interfaces-in-unity-dfb93b3537a5 19/24
07/06/24, 17:42 Hit System with Interfaces in Unity | by Jared Amlin | Nerd For Tech | Medium

Recommended from Medium

Hardik P

API Call in Unity


In this we will learn about how to call API in unity and set data in UI. For this we are using one
API which gives random user data.

5 min read · Dec 28, 2023

https://medium.com/nerd-for-tech/hit-system-with-interfaces-in-unity-dfb93b3537a5 20/24
07/06/24, 17:42 Hit System with Interfaces in Unity | by Jared Amlin | Nerd For Tech | Medium

Bruno Lorenz

Unity 3D: Implementing a Naming Convention for Your Unity Assets Files
Have you ever found yourself dealing with a multitude of assets in your project, only to realize
they don’t adhere to a consistent naming…

3 min read · Feb 28, 2024

Lists

Staff Picks
656 stories · 1020 saves

Stories to Help You Level-Up at Work


19 stories · 640 saves

Self-Improvement 101
20 stories · 1990 saves

Productivity 101
20 stories · 1793 saves

https://medium.com/nerd-for-tech/hit-system-with-interfaces-in-unity-dfb93b3537a5 21/24
07/06/24, 17:42 Hit System with Interfaces in Unity | by Jared Amlin | Nerd For Tech | Medium

SwiftRoll 🐦
Singleton Alternatives in Unity C#
Researching Dependency Injection (DI) and Service Locator

6 min read · Apr 23, 2024

12 1

Playtika Tech & AI

UNITY NATIVE: ANDROID LIBRARY PROJECT


By Artem Glotov
https://medium.com/nerd-for-tech/hit-system-with-interfaces-in-unity-dfb93b3537a5 22/24
07/06/24, 17:42 Hit System with Interfaces in Unity | by Jared Amlin | Nerd For Tech | Medium

7 min read · Mar 13, 2024

Lem Apperson

Beginning Game Development: Cinemachine 3.1.0


Unity Upgrades Cinemachine to 3.1.0: What You Need to Know

3 min read · Apr 29, 2024

https://medium.com/nerd-for-tech/hit-system-with-interfaces-in-unity-dfb93b3537a5 23/24
07/06/24, 17:42 Hit System with Interfaces in Unity | by Jared Amlin | Nerd For Tech | Medium

Simon Nordon

Unity Architecture: GameObject Component Pattern


In the last blog post we looked at the Spaghetti Pattern, a joke name used to describe a game
without any pattern at all.

9 min read · Jan 20, 2024

285 3

See more recommendations

https://medium.com/nerd-for-tech/hit-system-with-interfaces-in-unity-dfb93b3537a5 24/24

You might also like