- Home /
Interact with Objects around the player
So I made a method that shall damage Objects with the tag Enemy near the player. But it doesn't work correctly, i dont actually know why i made gave the enemy the tag player, and attached both scripts to player and enemy
public int damage = 50;
public float range = 1f;
private List <GameObject> enemys = new List <GameObject>();
void Update ()
{
if(Input.GetButton("Fire0"))
{
Attack();
}
}
protected void Attack()
{
Vector3 center = transform.position;
Collider[] hitColliders = Physics.OverlapSphere(center, range);
int i=0;
while(i<hitColliders.Length)
{
if(hitColliders[i].tag=="Enemy")
{
enemys.Add(hitColliders[i].gameObject);
}
i++;
}
for(i=0; i < enemys.Count; i++)
{
enemys[i].GetComponent<Enemy>().recieveDmg(damage);
}
}
public class Enemy : MonoBehaviour
{
public int life = 100;
void Update()
{
if(life == 0)
{
gameObject.SetActive(false);
}
}
public void recieveDmg(int damage)
{
life -= damage;
}
}
I only copied the important parts of the code, if you need anything more pls let me know :/
your check for the enemy dying where life reaches 0 will pretty much hardly happen as well as you simply do life -= damage in the receiveDmg function you will often end up below zero. To fix this you could just do this after applying damage in receiveDmg:
if(life < 0)
{
life = 0;
}
This is a common mistake I see in a lot of games too actually, where healthbars end up going off in the negative direction because of how their UI functions. So when the value goes below zero the "fill" is overdrawn to the left usually.
You might also want to clear your enemys List every time a new attack starts so that you dont call receiveDmg on outdated references to enemies. Unless your attack sort of clings to the enemies ofcourse.
Other than this I'm not sure what could be wrong here other than making sure that each object has the required tag and generally debugging to make sure your code is being executed at all using Debug.Log
I tested the code with the debugger and the code within the while-loop isn#t executed so i think the overlapSphere is giving 0 Objects to the array.
That could be because you have a range of 1 set in your script.
Your answer
![](https://koobas.hobune.stream/wayback/20220613195552im_/https://answers.unity.com/themes/thub/images/avi.jpg)