GameObject keeps colliding for sometime after being destroyed
I have 3 game objects: 1st is enemy, 2nd is player and 3rd is shield.
Enemy has a circle collider2d and IsTrigger checked.
Player has rigidbody2d + circle collider2d.
Shield has a circle collider2d and IsTrigger checked + it's Player's child(So it would move with Player). Shield's collider is slightly bigger than Player's collider.
When enemy hits a player(i.e player is inside trigger collider), then player takes damage, but if Shield gameObject is active, then Enemy collides with shield and shield's SetActive is set to false again and enemy disappears(Destroys), without touching Player's collider(Because as I said, shield's collider is slightly bigger, than player's, that's why enemy must first collide with shield's collider).
So here's the problem: By default Player's shield is SetActive(false) and when player receives a buff(pressing button B), then Player's shield SetActive is set to true. When enemy collides with shield, it sets the shield gameObject back to false(which is correct), but then also it damages the player, and then enemy disappears. Even when checking the console, it's shown that enemy first collides with shield, and then immidiately with the player(but sometimes for some reason it collides with player first, and then with the shield, maybe because player is moving?)But sometimes code works as intended, i.e shield disappears and player doesn't take damage(chance for correct work of OnTriggerEnter2D is 50%/50%, but if player moves at high speed, absolutely always enemy destroys the shield and damages player) Here's the code of the enemy:
private void OnTriggerEnter2D(Collider2D other) {
if(other.CompareTag("Player_Shield")){
Destroy(gameObject);
other.gameObject.SetActive(false); //turning off the shield
Debug.Log("Collided with shield");
}else if(other.CompareTag("Player")){
playerRef.TakeDamage(1);
Destroy(gameObject);
Debug.Log("Collided with player");
}
}
Answer by goodgamershow · Jun 29, 2021 at 10:16 AM
Since i never get help from answers.unity I went to unity forum and the solution to my issue was quite simple: if parent gameobject has rigidbody, children that have collider cause parent's rigidbody to work, which led to twice colliding. Here's the full post: link text