- Home /
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?
After doing a bunch of research on this and trying and failing, I've decided it's best to never insantiate GameObjects in the editor purely for the purpose of visualization. There's no reliable way to clean them up. $$anonymous$$y solution is a CustomEditor for my object and I represent the spawned prefabs with Handles. It means a car is represented by a cube in the editor, but there are no leaky GameObjects.
Answer by damianf · Apr 13, 2012 at 05:20 AM
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!
Your answer
Follow this Question
Related Questions
Editor OnSceneGUI - Capture click on Gizmo 0 Answers
Editor.OnSceneGUI never called. 3 Answers
If button highlighted 2 Answers
Display collider in scene view without object selected 6 Answers