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!");
}