I want my player to be able to inflict damage simultaneously on all enemies in range. The script to inflict damage is below and it works - but only on one enemy at a time. Once that enemy is killed, it starts hurting the next one. How can I make this inflict damage simultaneously on all?
{
EnemyHealth eh = (EnemyHealth)(GameObject.FindWithTag(“Enemy”).GetComponent(“EnemyHealth”)); //“eh” stands for enemy health in this script
eh.AdjustCurrentHealth((int)(-10));
}
Normally I would suggest adding enemies into a list when you instantiate them, but if you insist on using a Find, you can use the one that finds all with tags
Then loop through your array and check if they are in range and then deal damage.
You are finding an enemies health component and adjusting it by calling the AdjustCurrentHealth method. You are only getting one enemy which is why its not working on the second until the first dies. What you need to do is give the enemies different names for example Enemy1 and Enemy2
EnemyHealth eh1 = (EnemyHealth)(GameObject.FindWithTag(“Enemy1”).GetComponent(“EnemyHealth”)); //“eh” stands for enemy health in this script
eh1.AdjustCurrentHealth((int)(-10));
EnemyHealth eh2 = (EnemyHealth)(GameObject.FindWithTag(“Enemy2”).GetComponent(“EnemyHealth”)); //“eh” stands for enemy health in this script
eh2.AdjustCurrentHealth((int)(-10));
once you have two enemies in the game with unique names then you can find them and get the sciript component you want and adjust both of them.
Once you do that if you want to get the distance between two vectors use the Vector3.Distance method.
If you want to overlap sphere you can do something like
public void DetectEnemys()
{
Collider[] col = Physics.OverlapSphere(gameObject.transform.position, radius, layermask,
QueryTriggerInteraction.Collide); // Radius is how big you want the sphere to be, layermask will be in this case the layer in which enemies/npcs are on
if (col.Length > 0)
{
foreach (Collider hit in col)
{
if (hit.tag == "Enemy)
{
if (hit.gameObject.GetComponent<EnemyHealth>() != null)
{
hit.gameObject.GetComponent<EnemyHealth>().AdjustCurrentHealth((int)(-10));
}
}
}
}
}
you will want to linecast to the enemies detected with the overlapsphere to check if theyre accessible within the radius (doesnt go through walls etc)
Yes actually I would never use GameObject.Find but OP was already warned by two other people before me so I did not find it necessary to reiterate. I was merely trying to help OP get his question answered with what he had. Next time ill be sure to check with you Kiwasi before presenting any solutions. We cant have anyone using any code you do not find to be the most efficient possible.