How to get mouse click world position in the scene view in editor script?
I am trying to write an editor script for Unity Terrain that instantiates objects where I click on terrain in the scene view (pretty much like the tree generation of terrain). Input.GetMouseButtonDown(0);
appears to be not working in scene view.
How can i get the mouse button down event and the position of click in scene view in world coordinates?
Thanks.
Answer by FlightOfOne · Nov 26, 2018 at 04:24 PM
@Adam-Mechtley's, pointed me in the right direction. Here's what I came up with:
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
/// <summary>
///
/// </summary>
[ExecuteInEditMode]
public class ClickSpawn : MonoBehaviour
{
private void OnEnable()
{
if (!Application.isEditor)
{
Destroy(this);
}
SceneView.onSceneGUIDelegate += OnScene;
}
void OnScene(SceneView scene)
{
Event e = Event.current;
if (e.type == EventType.MouseDown && e.button == 2)
{
Debug.Log("Middle Mouse was pressed");
Vector3 mousePos = e.mousePosition;
float ppp = EditorGUIUtility.pixelsPerPoint;
mousePos.y = scene.camera.pixelHeight - mousePos.y * ppp;
mousePos.x *= ppp;
Ray ray = scene.camera.ScreenPointToRay(mousePos);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
//Do something, ---Example---
GameObject go = GameObject.CreatePrimitive(PrimitiveType.Cube);
go.transform.position = hit.point;
Debug.Log("Instantiated Primitive " + hit.point);
}
e.Use();
}
}
}
#endif
The Unity API supports different display scaling so this code that multiplies by pixelsPerPoint is required. I can confirm this code works with Unity 2018.3
Answer by Adam-Mechtley · Oct 24, 2016 at 08:54 AM
if (Event.current.type != EventType.MouseDown || Event.current.button != 0)
return;
// convert GUI coordinates to screen coordinates
Vector3 screenPosition = Event.current.mousePosition;
screenPosition.y = Camera.current.pixelHeight - screenPosition.y;
Ray ray = Camera.current.ScreenPointToRay (screenPosition);
RaycastHit hit;
// use a different Physics.Raycast() override if necessary
if (Physics.Raycast (ray, out hit))
{
// do stuff here using hit.point
// tell the event system you consumed the click
Event.current.Use ();
}
Answer by CoMANDOR · Oct 22, 2016 at 11:01 AM
The same problem I have. Just found this question on Google
Your answer
Follow this Question
Related Questions
Infinite floor with object as terrain. 1 Answer
Need Help instantiating GameObjects in an array using the middle mouse wheel. whew. 1 Answer
How to handle multiple terrains? 0 Answers
Mouse position from new InputSystem is not correct and is not the same as Input.mousePosition 0 Answers
Mesh Selection in Dropdown?? 2 Answers