I am attempting to detect the tag of the enemy collided with, and if its tag is Enemy, then access it's current health within its script (EnemyAI) and deduct the attack damage amount.
The code seems correct however i'm getting this error in Unity; "The name 'collision' does not exist in the current context".
I have multiple enemies and i've tagged all with Enemy. The idea being that if the player attacks one of them, it will detect that it's an enemy due to its tag and then access its script to apply the damage.
The code I currently have is:
//Detect enemies in range of attack
Collider[] hitEnemies = Physics.OverlapSphere(attackPoint.position, attackRange, enemyLayers);
//Hurt enemy
if (collision.gameObject.tag == "Enemy")
{
//Damage them
collision.gameObject.GetComponent<EnemyAI>().currentHealth -= attackDamage;
}
I also tried using public void OnCollisionEnter(Collision collision)
, adding the code to it and then calling it but I need to pass a value into it. I tried passing in Collider and I get an error saying its a type. I tried collider instead and I get the same error "The name 'collision' does not exist in the current context".
I'm stuck, i'd appreciate the help a lot.
I've reverted back to calling OnCollisionEnter(collision);
and then it goes to:
public void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "Enemy")
{
//Damage them
collision.gameObject.GetComponent<EnemyAI>().currentHealth -= attackDamage;
}
}
Same error message: The name 'collision' does not exist in the current context".
CodePudding user response:
You've mixed OnCollision syntax into your code. Currently there is no collision created/set anywhere in your code (context). There are only colliders that are returned by the overlapsphere. Hence why you get the error. You need to handle them a bit differently.
//Detect enemies in range of attack
Collider[] hitEnemies = Physics.OverlapSphere(attackPoint.position, attackRange, enemyLayers);
foreach(Collider enemyCol in hitEnemies){
//Hurt enemy
if (enemyCol.gameObject.tag == "Enemy")
{
//Damage them
enemyCol.gameObject.GetComponent<EnemyAI>().currentHealth -= attackDamage;
}
}