The overall hp = 3, so it repeats the code 3 occasions (the console reveals the log 3 occasions).
It looks as if you have misinterpreted how the code works. There’s nothing within the code that you have shared that may repeat based mostly on the quantity of HP that the enemy has. In different phrases, if the HP is 3 and also you’re seeing “DamageENEMYYYYYYY” 3 occasions in a console, it is a coincidence.
The code you have shared finds all colliders in a round space, will get the EnemyHP
element from every collider, and applies harm to every. If the message “DamageENEMYYYYYYY” seems within the console 3 occasions, that implies that Physics.OverlapCircleAll() discovered 3 totally different enemies. You can also make this extra apparent by together with details about the enemy in your console output:
foreach(Collider2D enemy in hitEnemies)
{
Enemy.GetComponent<EnemyHP>().TakeDamageEnemy(harm);
Debug.Log($"Apply {harm} harm to {enemy}", enemy);
}
Right here, we cross an interpolated string to Debug.Log()
; inside the interpolated string, we will embody variables inside braces, e.g. {harm}
will output the worth of the harm
variable.
Discover that I included a second argument to Debug.Log()
, the enemy
variable. The second argument is known as the “context”. If the worth we cross for the context is a GameObject or element, clicking on the log message within the Unity Editor will choose that GameObject/element. This makes it a lot simpler to rapidly discover the article {that a} log message is expounded to. On this case, for those who click on on the log message that claims “Apply […] harm to […]”, it should choose the enemy that the harm was utilized to.
Your present code has a design flaw – it should throw an error if there are any colliders within the round space that wouldn’t have the EnemyHP
element. Your code ought to seem like this:
foreach(Collider2D collider in hitEnemies)
{
var enemy = collider.GetComponent<EnemyHP>();
//this prevents an error if the collider does not have the EnemyHP element
if (enemy != null) {
enemy.TakeDamageEnemy(harm);
Debug.Log($"Apply {harm} harm to {enemy}", enemy);
}
}