- Home /
Collider 2d not working
Basically I made a box collider gameobject which is being enable and disabled by the animation. The problem is that a have a enemy which walks towards player when it is in range it plays attack animation. Because of the animation the hitbox is enabled first and disabled again and it applies damage to the player. But the problem is if the player doesn't do anything and just stands there the animation keeps playing the hitbox is enabled and disable again but it doesn't apply the damage. It is like the onTriggerEnter Function is not working when the player position isn't changed at all , even if the hitbox is disabled n then enabled again.
Answer by jiak1 · Sep 06, 2017 at 10:32 PM
Try using
void OnCollisionStay(Collision collision)
{
}
It gets called every frame for each collider that is touching it. Although it would be easier from your enemy script to call say an event on the player that damages it for example: In your enemy have:
void AttackPlayer()
{
//Play my animation
GameObject player = GameObject.Find("Player");
player.GetComponent<HealthScript>().takeDamage(20);
}
In your player have
void takeDamage(int amount)
{
health -= amount;
}
I tried collision stay/ ontriggerStay but the problem is it calls every frame and i have hitboxes that last for some time.
Try something like this but just check if can attack is true and each time you attack make sure to StartCoroutine(WaitForNextAttack()); which will wait in seconds the attackspeed and reset can attack back to true.
public bool canAttack = true;
public float attackSpeed = 5.0f;
IEnumerator WaitForNextAttack()
{
yield return new WaitForSeconds(attackSpeed);
canAttack = true;
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612134336im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
OnTriggerEnter2D not working 2 Answers
Trigger only one collider? 1 Answer
How to get the position of a Tile my Player collided with using OnTriggerEnter2D? 0 Answers
OnTriggerEnter2D is called 2 more times in Melee combat system 1 Answer
OnTriggerEnter2D fires multiple times when Animator component is on 3 Answers