OnDestroy() problem on Pickups

Hello,

When an enemy in the game dies I let a Pickup object spawn on its place. This Pickup is instantiated in the OnDestroy() Method. However when I go into playmode and then stop the game I receive hundreds of error messages and all these pickups remain in the scene instead of being destroyed. How can I get this right?

Error message and part of code would help

Code attached to GameObject (enemy):

void OnDestroy()
	{	Instantiate((GameObject)Resources.Load("PickupHealth", typeof(GameObject)),transform.position, transform.rotation);
	}

Error messages thrown:

  • Some objects were not cleaned up when closing the scene
  • !IsPlayingOrAllowExecuteInEditMode ()
  • Destroy may not be called from edit mode! Use DestroyImmediate instead.
    Also think twice if you really want to destroy something in edit mode. Since this will destroy objects permanently.

If I put the Instantiate code into DestroyImmediate I get no error messages, but not a single Pickup will be spawn in the game. So I guess my problem is the logic with the flow of things :face_with_spiral_eyes:

Ok, after finding another topic regarding the same problem I found out that the method “OnDestroy()” - although looking convenient - is practically unusable. I solved the issue now by invoking a method right at the moment before the enemy dies.

I just had this same problem. When I shut down the game, PanelManager would stay in the scene. This fixes it:

old code:

	void OnDestroy()
	{
		PanelManager.Instance.RemoveAnims( animData );
	}

new code:

	static bool isShuttingDown = false;
	void OnApplicationQuit()
	{
		isShuttingDown = true;
	}

	void OnDestroy()
	{
		if ( !isShuttingDown )
		{
			PanelManager.Instance.RemoveAnims( animData );
		}
	}