- Home /
Scripting a Click event in the Unity Editor
I'm trying to create a system to allow my fellow developers and me to place and position a bunch of objects within a given planar grid space, by clicking on it in the scene view of editor.
To do this, I have created a BoxCollider that is the exact size of the grid, to register the click. I would like to call the BoxCollider's Raycast function to then register the click. I have created a custom editor class to go along with it as well.
It seems that the best way to check for a click event would be in the OnSceneGUI function of my editor class. However, I have not been able to get any results from this approach.
As you can see in the code below, I have several methods to get the proper ray from the mouse position:
Camera.main.ScreenPointToRay (Input.mousePosition);
Camera.current.ScreenPointToRay (Input.mousePosition);
HandleUtility.GUIPointToWorldRay(Input.mousePosition);
none of these were able to register any collision with the boxCollider.Raycast function. Also, when the colision does happen.
Is OnSceneGUI the right place to try to be doing this?
How can I get a working ray from the mouse position, while in the Editor in the Scene view?
Also I am aware I am not checking for the actual click yet, leaving it out made it easier to identify that the ray is the issue.
Here is the code:
function OnSceneGUI(){
transform = (target as Transform);
var ray : Ray ;//= Camera.current.ScreenPointToRay (Input.mousePosition);
var hit : RaycastHit;
Debug.Log("ONSCENEGUI COLLISION CHECK TIME!!");
//ray = Camera.main.ScreenPointToRay (Input.mousePosition);
//ray = Camera.current.ScreenPointToRay (Input.mousePosition);
ray = HandleUtility.GUIPointToWorldRay(Input.mousePosition);
if (boxCollider.Raycast (ray, hit, 100000.0)) {
var pos = transform.InverseTransformPoint(hit.point);
var gridPos:Vector2 = new Vector2(pos.x / scaleProp.intValue , pos.y / scaleProp.intValue);
Debug.Log("CLICK ON SHIP GROUP AREA: "+ pos);
Debug.DrawLine (ray.origin, hit.point);
}
}
Answer by nsxdavid · Mar 16, 2013 at 11:02 PM
This'll give you an idea how to get a ray in editor mode (in C#):
void OnSceneGUI()
{
Event e = Event.current;
Ray ray = Camera.current.ScreenPointToRay(e.mousePosition);
Debug.DrawRay(ray.origin, ray.direction, Color.blue,10);
}
This does absolutely nothing in my scene. Is there something else I need to do to get that to work? $$anonymous$$ust i tell the script to ExecuteInEdit$$anonymous$$ode?
Any advice is appreciated thanks :)
yes you need ExecuteInEdit$$anonymous$$ode for OnSceneGui to be called.