Select and focus items in Scene View by script

Select and focus items in Scene View by script.

I have a minor inspector script that selects GameObject that matches certain ID. But I’d really want it to work in Scene View not in Game View. What could I do?

Pretty sure you are looking for this: Unity - Scripting API: ExecuteInEditMode
The ExecuteInEditMode attribute makes a Monobehavior script run in the scene view as well.

That makes script run in Editor Mode and I’m looking for manipulating Scene View camera, for this I need a reference and an API.

As a rule of thumb, if something works in Game View but not in Scene View, then that’s because Monobehavior Scripts are not running in Scene View. Which means that ExecuteInEditMode should solve your problem, since it enables those scripts that run in Game View but not in Scene View, to also run in Scene View.

From what you wrote now i get that you (seemingly?) want to control the scene view camera. Combining all the previous information, there were only two words slightly indicating that this may be the case (“focus” in the title and “inspector” in the post, both of which can mean a gazillion things depending on the context) so you may wanna specify your problem in a bit more detail next time.

Anyways, you can get the reference to the scene view camera by calling SceneView.camera. However, if this is the only thing you needed, then that’s literally the first result when you google these 3 words, so that may have been faster ^^

You’ll still need the ExecuteInEditMode attribute if you use scripts to control the camera.

To select something in “scene view” (ie have it selected), you use the Selection class.

There’s a bunch of methods to focus stuff in the SceneView class API.

What you want is probably:

Selection.activeTransform = target;
SceneView.lastActiveSceneView.FrameSelected();
7 Likes

Since Unity 2018.2 you can also focus (frame) objects by passing some bounds, instead of changing the active selection.

Vector3 position = Vector3.zero;
Vector3 size = Vector3.one;

Bounds bounds = new Bounds(position, size);

SceneView.lastActiveSceneView.Frame(bounds, false);