Basically: i’m setting up a game in which an enemy run to a tomato plant, and when it reaches it then it start attacking it. If the enemy stop touching the plant then the attack stop. (I omitted part of the code about the attacking every few seconds.)
The problem i run into is that if the enemy touches anything, then it start attacking the plant, even if it doesnt touch it directly:
example. the enemy starts moving, i run with my player into the enemy to block it, but for some reason the enemy can still attack the plant even if it’s not in contact.
As i programmed it, my basic thinking is “when the enemy touches the plant, it gets the component script of the plant, so that it knows what to attack” but i don’t know why, the enemy knows what to attack even before touching it.
can you tell me how to fix this?
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision = Objective)
{
target = collision.GetComponent<Tomato_Plant>();
touching = true;
Debug.Log(touching);
}
}
private void OnCollisionStay2D(Collision2D collision)
{
contact = collision;
if (contact != null)
{
Attack();
}
else
{
contact = null;
}
}
private void Attack()
{
if (contact != null)
{
if (touching == true)
{
target.TakeDamage(damage);
Debug.Log("Plant took damage");
}
}
else
{
touching = false;
}
}
}