How to run code when an object is placed in the editor?

I’m building a 2D game where the action happens in the x-z plane. When working in the editor and placing an object in my scene, the objects get unpredictable Y values which I then have to correct to 0 so that they look correct in the editor (I have attached a script to them which guarantees y=0 in PLAY mode). How can I ensure that all my objects are placed with y=0? My idea was to attach a component with a script to my prefab and then place objects via prefab, but I don’t know how to make a script attached to an object run code in the editor at the time the object is placed in the scene.

There are MonoBehaviours that you can instruct to run while in Editor mode:

Just write a MonoBehaviour like in this example:

Another way (which I do not recommend, but will still work) is to abuse a function that is called in Editor Mode to execute your script, such as OnDrawGizmos().

I don’t know how you could correct your gameObject in the exact moment you are placing them in the Editor, but I think you could set the y position of every gameObject in your scene (or only of the desired gameObjects) to 0 in every update. An update in the Editor mode occurs if there is a user input, such as a mouse movement or click.

In your code you could write something like:

var gameObjects = GameObject.FindObjectsOfType<YourType>();
foreach (var object in gameObjects) }{
   object.transform.position = new Vector3(object.transform.position.x, 0, object.transform.position.z);