- Home /
The question is answered, right answer was accepted
2D triggers not working
Here's the code:
private void OnTriggerEnter2D(Collider2D col)
{
switch(col.gameObject.name)
{
case "sightTrigger":
seesPlayer = true;
inSightTrigger = true;
break;
case "attackTrigger":
rb.AddForce(-rb.velocity);
seesPlayer = false;
Invoke("attackScript", 1);
seesPlayer = true;
Invoke("sightCheck", 1.5f);
break;
}
// I tried it with this if statement as well
//if(col.gameObject.name == "sightTrigger")
//{
// seesPlayer = true;
// inSightTrigger = true;
//}else if(col.gameObject.name == "attackTrigger")
//{
// rb.AddForce(rb.velocity);
// seesPlayer = false;
// Invoke("attackScript", 1);
// seesPlayer = true;
// Invoke("sightCheck", 1.5f);
//}
}
// The functions it calls in case that helps:
void sightCheck()
{
if(!inSightTrigger)
{
seesPlayer = false;
}
}
void attackScript()
{
Collider2D[] thingsHit = Physics2D.OverlapCircleAll(attackPoint.position, attackRange, player);
foreach(Collider2D thing in thingsHit)
{
thing.GetComponent<player>().takeDmg(attackDamage);
}
}
Here's what the triggers look like: (sightTrigger is the large green box, attackTrigger is the small one in the corner of it, the red square is what the triggers are attached to, and the brown square that's inside the trigger is the player.)
sightTrigger worked before I set up the onTriggerEnter2D to be able to hold multiple triggers but stopped afterwards.
Answer by Inline2 · Sep 08, 2020 at 08:19 AM
I fixed it by making sightTrigger and attackTrigger into boxCollider2D variables and using isTouching, as I figured out that col is the thing that entered the trigger not the trigger. example:
col.isTouching(sightTrigger)
Answer by BenWiller1989 · Sep 04, 2020 at 10:44 PM
Does the script holder have an Rigidbody 2d?
Yes, both the red square and the player have a rigidbody 2d
Follow this Question
Related Questions
Why is my Collider Broken? 0 Answers
why OnTriggerEnter2d runs four-time? 0 Answers
How to Destroy specific objects using OnTrigger2D? 1 Answer
OnTriggerEnter and OnTriggerExit both trigger twice 0 Answers