Execute code only when object is selected in editor or scene view

I have a script to use only inside the editor.
How do I make code only run on a object that is selected / being moved around in the scene?

3 Answers

3

You should look into the examples and demos of extending the editor and the Editor class. I’m not that familiar with UnityScript, but a custom editor for one of your class should look like this:

// MyClassEditor.js
@CustomEditor (MyClass)
class MyClassEditor extends Editor
{
    function OnInspectorGUI ()
    {
        DrawDefaultInspector();
    }
    function Update()
    {
        // ...
    }
}

Inside this class you have the target variable which holds the reference to the classinstance you’ve selected.

Note that Update isn’t called periodically. It is called when something changed (you moved the camera, an object). If you need a periodically event There’s also a delegate in EditorApplication

I doesn't appear that Update is a valid callback on Editor classes. In the docs, it refers to using Update on the actual MonoBehavior, along with @script ExecuteInEditMode().

Ok got it figured out, OnSceneGUI() in a editor script can be used to do things when the specific object is selected in the scene.

You didn't specify what you want to do when the object is selected. OnSceneGUI is a gui callback that allows you to render GUI elements inside the SceneView. OnSceneGUI is like OnGUI called for different events. For a general purpose you should use Update().

I think you’d have to use another script

in C#:

if (Editor.target == ObjWithScript)
    ObjWithScript.GetComponent<ScriptName>().enabled = true;

I can't add this code anywhere in JS without having a compile error. tried my update function, tried the editor script for my script. if(Editor.target == transform) An instance of type 'UnityEditor.Editor' is required to access non static member 'target'.

This example is in C# and not in UnityScript(JS). I can't find any hint in your two sentences that you're using UnityScript. Furthermore this fragment indeed doesn't make much sense to me ;)