Creating a new Object calls OnInspectorGUI()

I have a custom GUI for script “foo” that uses the OnInspectorGUI() function. When a bool in the custom inspector is true it calls a function from inside the class that the custom inspector is for.

[CustomEditor(typeof(Foo))]
public class FooInspector : Editor
{
    public override void OnInspectorGUI()
    {
        serializedObject.Update();
        Foo FooObject = (Foo)target;
        if(FooObject.foobar)
        {
            fooObject.fooFunction();
        }
    }
}

The class function creates a new game object, which for some reason calls OnInspectorGUI(), which makes it create a new game object again which causes an infinite loop.

public class Foo : MonoBehaviour
{
    public void fooFunction()
    {
        GameObject GO = new GameObject();
    }
}

I can’t figure out what is calling OnInspectorGUI() when I create a new game object and how to stop it from being called. I’m guessing some event is generated when the scene is changed that repaints the inspector.
How do I stop the event from happening in this instance or stop the infinite loop?

Maybe this has already been answered in the forums somewhere but I wasn’t exactly sure how to ask about it. Thank in advance.

Don’t you just need to set foobar to false?? Or else have another bool that says “I did create a foo Go so don’t make any more.”

That would be a good work around but I want the inspector to still display that foobar is true. If I comment out the line in fooFunction that creates a new game object it doesn’t update the scene and it doesn’t repaint the inspector which doesn’t create an infinite loop. I do want it to create more objects, but only when I change one of the parameters in the inspector GUI for that class.

Hi @bassbeast

What exactly are you trying to do or achieve?

If you simply want to create objects from your custom editor, couldn’t you add an if with a button in it, then when user press that button, in if block call a method in your class, and it creates the game object?

I’m trying to find out what is calling OnInspectorGUI() after creating a game object to see if I can disable updating the GUI every time a game object is created in this instance. I don’t want a work around. I know about buttons, I’m using one in fact that works just fine.