Collision2d race condition on enemy death
I have gates in my game that cause an explosion on each of their two edges (identical to this: https://www.youtube.com/watch?v=OKfG_OoiZrw).
On an enemy death, I want to call the die() function of the EnemyController. So I added a circle collider to my GateExplosion, and use this simple code:
private void OnTriggerEnter2D(Collider2D collider2D)
{
if (collider2D.CompareTag("Enemy"))
{
EnemyController c = collider2D.gameObject.GetComponent<EnemyController>();
c.die();
}
}
Code from EnemyController:
public void die()
{
for (int i = 0; i < numScoreDrops; i++)
{
GameObject newScore = Instantiate(scoreObject, transform.position, Quaternion.Euler(new Vector3(0f, 0f, Random.Range(0f, 360f))));
}
Destroy(gameObject);
}
However, I noticed that sometimes it will drop double the number of score drops. I think this is because both collisions happen simultaneously and call die() twice. How can I avoid this race condition?
Also, the collider itself is pretty inconsistent, but I think that is unrelated to this issue. Thanks!
Answer by superweeniehutjr · Apr 12, 2021 at 05:05 PM
I'm dumb, I had reworked the logic of my game a little bit and didn't think to just check for the collision inside the enemy script instead of the gate explosion script. Fixed my problem and the other inconsistency I mentioned.
Your answer
Follow this Question
Related Questions
Why are my keys being registered multiple times? 1 Answer
Destroy shattered objects after being smashed. 0 Answers
Change Vertex Color with Condition 0 Answers
Jump Script Doesn't Affect my Player 0 Answers