Move scene camera to gameObject via Editor script

When you double click on object in hierarchy view the scene camera moves to this object on scene and adjust it’s size to fit the object size.

I need to acheive this through Editor script (in custom inspector, by button click). I don’t neet this object to be selected in Inspector though, just ping it in hierarchy with EditorGUIUtility.PingObject

Wow-wow I made it!

if (GUILayout.Button(i.ToString(), EditorStyles.toolbarButton, GUILayout.Width(20)))
{
	EditorGUIUtility.PingObject(item);

	var currentlActive = Selection.activeGameObject;
	Selection.activeGameObject = item.gameObject;

	SceneView.lastActiveSceneView.FrameSelected();

	Selection.activeGameObject = currentlActive;
}

It works like a charm! It even keeps current hierarchy scroll position of selected object! Regardless of that I swap selected objects. Phew :slight_smile:

Hello!

Unity provides a function which will take a Vector3 and automatically lerp the scene view camera to that position as if it’s being focused on via the Unity UI. Example below:

SceneView.lastActiveSceneView.LookAt(nextSceneViewPos);

Hope that helps some people :slight_smile:

If you want to move the camera to an specify GameObject, you can use the Vector3.Lerp function. You can find all the info about this in here: Unity - Scripting API: Vector3.Lerp

But in the end, it takes 3 parameters:

  1. the initial position of the gameObject (From Vector3)
  2. The destination of the gameObject (To Vector3)
  3. The speed you want to move the gameObject (for this you can setup a var like speed and then you can use “speed * Time.deltaTime”)

Hope this helps!