- Home /
How to get the enemy my player touches when he attack?
Hello, Let's say my player as a sword and when I left click he swing his sword and attack the enemy in front of him.
(I don't click on the enemy, in fact I don't have the cursor showing at all so using raycast isn't an option).
I want now to damage that specific enemy and I don't know how to get that enemy health in my combat script.
Any ideas?
Answer by Llama_w_2Ls · Aug 07, 2020 at 12:02 PM
Im assuming that each enemy has a different name and that each one has a script containing their individual health and stats. You could do this by attaching a script to your sword, and if it collides with an enemy, then do damage, as well as access their stats script. For example:
private void OnCollisionEnter(Collision collision)
{
if (collision.collider.gameObject.CompareTag("Enemy")) //If my sword collides with an enemy:
{
GameObject enemyThatIHit = collision.gameObject; //Stores the enemy's information into a local gameObject
HealthScript enemyHealth = enemyThatIHit.GetComponent<HealthScript>(); //Gets the enemy's health script
float HealthOfEnemy = enemyHealth.health; //Gets the enemy's health
}
}
Hope it works! @dddaniel159
Unfortunately it doesn't work. I made sure I have "Enemy" tag on my enemy and currently I have only one enemy and he has stats script attached to it with health and takeDamage method. This is my code:
private void OnCollisionEnter(Collision collision) { if (isAttacking && collision.collider.gameObject.CompareTag("Enemy")) { GameObject target = collision.gameObject; EnemyStats TargetHealth = target.GetComponent<EnemyStats>(); TargetHealth.TakeDamage(damage); } }
Does your player have a rigidbody to detect collisions in the first place? Sorry for taking so long to respond, but the most likely reason is that your player never collides with the enemy.
I don't use rigidbody on my player because I use character controller. I thought that collider will do the job. So how should my player detect collisions without rigidbody?
Your answer
![](https://koobas.hobune.stream/wayback/20220613005043im_/https://answers.unity.com/themes/thub/images/avi.jpg)