Instantiate GameObject Editor in center of the "Scene"

Hi guys, I was wondering how to instantiate an object from the Editor in the center of the View “Scene” screen.

        string path = "Assets/Resources/teleports/updated/Teleport.prefab";

        GameObject go = AssetDatabase.LoadAssetAtPath(path, (typeof(GameObject))) as GameObject;
        PrefabUtility.InstantiatePrefab(go);

go.transform.position = "center of the scene view in editor"

Thank you!

@antonioperez80

You could get the screen center and convert it to world position, but if you don’t have some specific floor/world plane, you have to define some distance from camera to place the object (probably not exactly where user expects) or do a raycast to get an exact hit to some world location.

This work for me! Thank you!

using UnityEditor; 

void instantiate_teleport()
    {
        Selection.activeObject = GameObject.Find("any object in the scene no matter which");
        string path = "Assets/Resources/teleports/updated/Teleport.prefab";

        GameObject go = AssetDatabase.LoadAssetAtPath(path, (typeof(GameObject))) as GameObject;
        var goe = PrefabUtility.InstantiatePrefab(go) as GameObject;       
          
        Camera view = UnityEditor.SceneView.lastActiveSceneView.camera;
        Debug.Log(view);
        Vector3 pos = view.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, 0f));

        goe.transform.position = pos;
        Selection.activeObject = goe;

        SceneView es = UnityEditor.SceneView.lastActiveSceneView;
        es.AlignViewToObject(goe.transform);

     
    }
1 Like