If I create GameObjects in OnSceneGUI, how can I destroy them when my control is no longer selected?

I have a GameObject / AI marker that creates + destroys prefabs during gameplay (Spawns a group of AI when camera is close, unspawns them when camera goes away). I want to view the spawned AI in Scene View when I select the parent marker (currently doing this with OnSceneGUI) but they get leaked when the marker is no longer selected. Can anyone suggest how/where to clean them up when the marker is not selected?

I’m experimenting with this right now. So far, I have an “okay” solution. (Scott, probably too late for you, but maybe not for the next poor sap?)

Basically, I do this:

public void OnEnable()
{
    m_MyGameObject = ...;
}

public void OnDisable()
{
    if (m_MyGameObject != null)
    {
        Object.DestroyImmediate(m_MyGameObject);
        m_MyGameObject = null;
    }
}

You will see that there are holes here…like, saving while the object is selected and then crashing, or something like that. If you can enforce that m_MyGameObject is parented to something that should never start the game with children, you can detect that in an Awake() call in a script on that object, warn, and delete the objects to be safe.

It’s not remotely what I would call elegant, but it may be better than using handles. Also I’ve only just started doing this, so YMMV!