- Home /
Instantiate object in middle of Editor Scene View
I'm creating a tool that instantiate spawnPoint by clicking a GUILayout.Button. I want to instantiate it at the middle of the Editor Scene View and not always at Vector3(0f,0f,0f).
The tool is not for InGame only for production.
Thank you!
Just to help other to have an idea of how we can do it. The function instantiate an object on top of the gameobject that raycast hit from the middle of the Editor Scene view.
(Little work to do on it, because if the hitted GameObject have a X or Z rotation, the instantiated object isn't exactly positionned on top of it)
//Instantiate a spawnPoint at the middle of the screen on the object that raycast hit
void SpawnInstantiating ()
{
// Check if sceneView is the current drawing one
if (SceneView.currentDrawingSceneView == null){
Debug.Log ("Click on scene view before adding a spawnPoint!");
return;
}
//Cast a ray from the middle of the screen
Camera sceneCam = SceneView.currentDrawingSceneView.camera;
Vector3 rayPos = sceneCam.ViewportToWorldPoint (new Vector3 (0.5f, 0.5f, 1000f));
Ray ray = new Ray (sceneCam.transform.position, rayPos);
RaycastHit hit;
if (Physics.Raycast (ray, out hit, Mathf.Infinity)) {
//Check if object it isn't the background. If True instantiate spawnPoint on object hit
if (hit.collider.tag != "Background") {
Vector3 spawnPos;
//If object tag isn't floor, add lossyscale/2 to ajust the Y position of the spawnPoint
if (hit.collider.tag != "Floor")
spawnPos = new Vector3 (hit.point.x, hit.collider.bounds.center.y + (hit.transform.lossyScale.y / 2f), hit.point.z);
else
spawnPos = new Vector3 (hit.point.x, hit.collider.bounds.center.y, hit.point.z);
GameObject _go = Instantiate (Resources.Load ("SpawnPoint"), spawnPos, Quaternion.identity) as GameObject;
_go.name = "Unassigned_SpawnPoint";
Selection.activeGameObject = _go;
} else
Debug.Log ("Need to point a Gameobject!");
} else
Debug.Log ("Need to point a GameObject!");
}
Apologies for resurrecting this, but there's an easier and better way built-in to Unity. Use SceneView.$$anonymous$$oveToView as defined here: https://docs.unity3d.com/ScriptReference/SceneView.$$anonymous$$oveToView.html
SceneView.lastActiveSceneView.$$anonymous$$oveToView(transform);
Answer by rutter · Apr 16, 2012 at 11:39 PM
You could use `Camera.ViewportToWorldPoint()`, passing in a vector like (0.5, 0.5, 1).
If you're in-game, you'll usually want to do this with `Camera.main`. In-editor, last I knew, most people use `Camera.current` to get the scene view camera, but if that doesn't work you can try some searches like "How do I find the scene view camera in the Unity editor?"
Nice! Thank a lot. Just need to add some line to ajust it well.
Selection.activeObject = SceneView.currentDrawingSceneView;
Camera sceneCam = SceneView.currentDrawingSceneView.camera;
Vector3 spawnPos = sceneCam.ViewportToWorldPoint(new Vector3(0.5f,0.5f,10f));