How to target a specific colider
So I'm currently making a top down RPG for a school project, and my attack script uses a polygon collider that looks for the collider on the enemy to attack when space is pressed. Only problem is, in making the enemy AI, I had to make another collider for the enemy so that they could find and follow the player. When the attack script is run, it attacks both colliders. Is there a way I can make the script only attack the box collider? script for enemy pathfinding, and both attack scripts found below
Enemy targeting
public class enemyTargeting : MonoBehaviour
{
public float speed = 2.5f;
private Transform target;
private void Update()
{
if (target != null)
{
float step = speed * Time.deltaTime;
transform.position = Vector2.MoveTowards(transform.position, target.position, step);
}
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "Player")
{
target = other.transform;
}
}
private void OnTriggerExit2D(Collider2D other)
{
if (other.gameObject.tag == "Player")
{
target = null;
}
}
}
Player attack
public class playerAttack : MonoBehaviour
{
private GameObject attackArea = default;
private bool attacking = false;
private float timeToAttack = 0.25f;
private float timer = 0f;
void Start()
{
attackArea = transform.GetChild(0).gameObject;
attackArea.SetActive(false);
attacking = false;
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
Attack();
}
if(attacking)
{
timer += Time.deltaTime;
if(timer >= timeToAttack)
{
timer = 0;
attacking = false;
attackArea.SetActive(false);
}
}
}
private void Attack()
{
attacking = true;
attackArea.SetActive(true);
attackArea.SetActive(attacking);
}
}
area of attack
public class areaOfAttack : MonoBehaviour
{
private int damage = 1;
private void OnTriggerEnter2D(Collider2D collider)
{
if(collider.GetComponent<enemyHealth>() != null)
{
enemyHealth health = collider.GetComponent<enemyHealth>();
health.TakeDamageE(damage);
}
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613053426im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Trigger Sets GameObject 0 Answers
Lightning that tracks enemies with range in a 2d topdown 0 Answers
2D topdown RPG shooting in facing direction 0 Answers
Suptract 2 areas and spawn objects in resulting area 1 Answer
2D Top Down Combat: How to only damage enemy that the player is facing? Up,down,left,right 1 Answer