How to destroy on exiting PlayMode/EditMode?

Hi, Im new to the Unity framework, and having some issues.

Im instantiating an array of GameObjects from code in the Start().

Tiles = new GameObject[SizeX, SizeZ];
for (int x = 0; x < SizeX; x++)
    for (int z = 0; z < SizeZ; z++)
        var tile = (GameObject) Instantiate(TileTemplate, new Vector3(x, 0, z), Quaternion.identity);
        tile.GetComponentInChildren<Renderer>().enabled = false;
        Tiles[x, z] = tile;

Where TileTemplate is a public GameObject.
The GameObjects are instantiating as they should, and Scripts are running fine.

The problem occurs when I´m exiting PlayMode.
The GameObjects are persisting them selvs in the editor, and are duplicated the next time I start PlayMode.

One thing is that I dont totally understand why (Editor state-full?), but ok.

So I´m then looking for something like Stop() or or onApplicationStop() which do not exist, but find my way to

EditorApplication.playmodeStateChanged += PlaymodeStateChanged;


private void PlaymodeStateChanged()
	if (!EditorApplication.isPlayingOrWillChangePlaymode &&
            EditorApplication.isPlaying )
		foreach (var tile in Tiles)      
		Tiles = null;

And its not working… the method is called and the foreach loop is running, but its not destroying the GameObjects.

So I wonder is my code faulty, or is there something fundamental of the Unity framework I got wrong?

Hi! If something is instantiated in that way inside a MonoBehaviour’s Start () function, then it should automatically get cleaned up when the editor stops playing. You don’t have something like ExecuteInEditMode on your script, do you?