- Home /
MissingReferenceException: The object of type 'CircleCollider2D' has been destroyed but you are still trying to access it.
I'm getting this error when I run my game: MissingReferenceException: The object of type 'CircleCollider2D' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object.
When I run my game, everything works perfectly fine and I'm not sure where this error is coming from.. I was hoping one of you amazing people could take a look and shed some light!
Here is the code:
public class EnemyAttackGen1 : MonoBehaviour {
public GameObject attackEffect;
public int damageAmmount = 20;
IEnumerator OnTriggerEnter2D(Collider2D enemy) {
if (enemy.tag == "Enemy") {
yield return new WaitForSeconds(0.5f);
if (GetComponent<Generator>().open) {
GetComponent<Generator>().currentHealth -= damageAmmount;
}
Instantiate (attackEffect, enemy.gameObject.transform.position, enemy.gameObject.transform.rotation);
Destroy(enemy.gameObject);
}
}
}
Let me know if you need more information! Thank you in advance
Sounds like your enemy is destroyed within the 0.5 seconds of wait time that you have. Not sure though, it's hard to tell.
I am having the same error I dont understand why my program is calling destroyed object
We can't help if you don't show the portion of the script that is causing the error and also the error itself.
Answer by VladimirTa · Aug 12, 2020 at 01:04 AM
That's because you are colliding with the same "enemy" more than once. While the coroutine is waiting 0.5 seconds, you keep colliding with the same object, and when the time comes for the same object the second time, it is already destroyed. You need to add some checks to make sure to collide with the enemy only once. Maybe disabling the collider on the enemy before waiting. Also some optimization tips. If you are using WaitForSeconds more then once, instead of using a new one each time, cache it first, you will save some resources on garbage collection.
This comment helped me understand why the error was co$$anonymous$$g up. Thank you so much, the issue has been resolved on my end!
Your answer
![](https://koobas.hobune.stream/wayback/20220613005348im_/https://answers.unity.com/themes/thub/images/avi.jpg)