2
\$\begingroup\$

What I want is a way that an editor script can tell when it has been attached to an object in the scene.

OnEnable() and Awake() only happen when you bring an object with the editor script attached to it up in the inspector.

Is there any built in method to accomplish this? Or perhaps some work around? The editor script only needs to tell when itself has been added to an object, not any other components.

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

If you add the attribute [ExecuteInEditMode] to the script, just before the script class name, it will be run in editor mode. These tagged scripts will have their Start() function called (and I believe the OnEnable() and Awake(), though I haven't tested it), and a few others given some conditions:

  • Update is only called when something in the scene changed.
  • OnGUI is called when the Game View recieves an Event.
  • OnRenderObject and the other rendering callback functions are called on every repaint of the Scene View or Game View.

For example:

using UnityEngine;
using System.Collections;

[ExecuteInEditMode]
public class Example : MonoBehaviour {
    public Transform target;
    void Update() {
        if (target)
            transform.LookAt(target);

    }
}
\$\endgroup\$
2
  • \$\begingroup\$ This is useful, the main problem is I don't want some of the functions of the main script running in the editor. I have a script for in the game, with a custom editor. And I was wanting the custom editor script to be able to do something on start. \$\endgroup\$ Commented Mar 26, 2014 at 18:22
  • \$\begingroup\$ @TimothyWilliams When using ExecuteInEditMode, how can I tell if game is playing? \$\endgroup\$
    – House
    Commented Mar 26, 2014 at 18:24

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .