# How to prevent creation of game object clones

Within the script of one game object I am initializing another game object with a prefab. To make development easier (so I don't have to run the game for every change) I call the function in OnValidate(). Anytime I select the hasWindow bool a Window clone is created. So in situations that I select then deselect (doesn't go away) and reselect, two clones are created. I don't even have a window game object in my hierarchy, so I don't get why any clone is created. I want the window to appear when I select hasWindow and disappear (not hide) when I deselect within the inspector. How can I do this? The relevant code follows:

public bool hasWindow;

void OnValidate ()  {
prepareWindow();
}

void prepareWindow  ()  {
if (hasWindow) {
}

}


You need to destroy the previous instantiated window, i'm assuming you run this in EditMode? That's why we need to use DestroyImmediate. Also, the (clone) thing, it's just a naming convention, every instantiated object has it. You can change it,

window.name = "Window";


void prepareWindow  ()  {
if (hasWindow) {
}
else if (window != null)
UnityEditor.EditorApplication.delayCall += () =>
{
DestroyImmediate(window);
};
}


Edit: I would personally activate and deactivate the window, but it's up to you.

Edit2: When using the OnValidate callback, it looks like you can't Destroy components right away, but i found this solution with delayCall.

• I got this error Destroying GameObjects immediately is not permitted during physics trigger/contact, animation event callbacks or OnValidate. You must use Destroy instead. Then when I changed to Destroy I got this error 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. UnityEngine.Object:Destroy(Object) – SuperHyperMegaSomething Jun 29 '17 at 18:18
• Edited the answer. – Guilherme Junqueira Coutinho Jun 29 '17 at 23:48

How about only creating the window if it doesn't already exist?

void prepareWindow  ()  {
if (hasWindow && window == null) {