Running this code, sometimes the Update() crashes with
NullReferenceException: Object reference not set to an instance of an object
Enemy.Update () (at Assets/scripts/Enemy.cs:36)
I think that the Enemy object got destroyed while its Update method was still running.
Is that possible?
Doesn’t the Unity Engine prevent that, and destroys the object only outside of Update and FixedUpdate?
If the mainCannon is attached to the object that contains this script, the problem is that you are destroying the object, and Unity takes one frame to destroy the object, in the frame that you call the Destroy(gameObject), the object is marked for destruction, and if you check for nullity it will return null.
In the next frame, the object is released from memory.
Try this:
private void OnTriggerEnter2D(Collider2D collision)
{
Debug.Log("OnTriggerEnter2D " + collision);
if (collision.gameObject.CompareTag("projectile_player"))
{
//Destroy the bullet and the enemy itself.
Destroy(collision.gameObject);
Destroy(gameObject);
}
}